C#_图片在Access数据库中的读入与读出

前言

  最近在做C#大作业的时候需要添加了一个功能,就是每个用户都可以选择自己喜欢的头像,在登陆之后用户可以在主界面内看到自己的头像。我使用的是Access数据库。

实现方法

  思路:将图片以分解为二进制流存入数据库,读取的时候再将数据库中的二进制流转换为图片就OK。

将图片存入数据库的代码

1
2
3
4
5
6
7
8
9
10
MemoryStream stream = new MemoryStream();
byte[] photo = null;
Image img = this.pictureBox1.Image;//将picturebox中的图片定义为一个Image对象
img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
photo = stream.ToArray();
stream.Close();
string sql = "UPDATE employee set[touxiang] =@img where [username]='" + username.Text + "'";//将图片存入数据库的sql命令语句(touxiang是我在数据库中起的列名,根据username将图片存入相对应的用户下面。)
OleDbCommand comm = new OleDbCommand(sql, conn);
comm.Parameters.Add("@img", OleDbType.VarBinary, photo.Length).Value = photo;
comm.ExecuteNonQuery();

将图片从数据库中读出来的代码

1
2
3
4
5
6
7
8
string sql = "Select touxiang From employee Where[UserName]='" + bianhao + "'";
OleDbCommand comm = new OleDbCommand(sql, conn);
OleDbDataReader sdr = comm.ExecuteReader();
sdr.Read();//从数据库中读取
MemoryStream ms = new MemoryStream((byte[])sdr[0]);
Image image = Image.FromStream(ms);
sdr.Close();
pictureBox1.Image = image;//将图片放到picturebox中

Attention

头文件中一定还要加上

using System.IO

在数据库中一定要设置头像列的数据类型为OLE对象,如下图所示:

坚持原创技术分享,您的支持将鼓励我继续创作!
-------------本文结束感谢您的阅读-------------
显示 Gitment 评论
0%