编程高手帮下忙~ C# 图片存入数据库的问题 为什么要将二进制读入到字节数组中

来源:百度知道 编辑:UC知道 时间:2024/06/23 14:16:56
public void SaveImage(OpenFileDialog openf, string ygbh)//将图片以二进制形式存入数据库中
{
string str = openf.FileName.ToString();
FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imagebytes = br.ReadBytes((int)fs.Length);
con.Open();
SqlCommand cmd = new SqlCommand("update TABLE_employee Set 员工照片=@Photo where 员工编号='" + ygbh + "'", con);
cmd.Parameters.Add("@Photo", SqlDbType.Binary).Value = imagebytes;
cmd.ExecuteNonQuery();
con.Close();
}
再麻烦帮我详细一点解释一下最后3句。
public void GetImage(PictureBox pb, string ygbh)//获得数据库中图片
{
byte[] imagebytes = null;
SqlDataAdapter sda = new SqlDataAdapter("select * from TABLE_employee where 员工编号='" + ygbh + "'", con);
DataSet ds = new DataSet();
sda.F

因为储存图片的话,那么数据库中字段肯定是Image的,对应的就是byte[]啊.

//把读取出来的byte[]转化成内存流
MemoryStream ms = new MemoryStream(imagebytes);
//通过内存流构造一个Bitmap
Bitmap btmp = new Bitmap(ms);
//设置PictureBox的Image属性为刚刚通过byte[]形成的Bitmap
pb.Image = btmp;

一般都是这种读取方式,因为你在数据库的字段格式就image格式。
MemoryStream 是一种无格式的内存流,用来读取图片,
Bitmap 封装位图,把图片内存流转换成图片格式。
pb应该是picturebox。接收图片。

这是固定的存储格式,要存储图片到数据中都要如此操作。

你可以理解为一个固定的语法吧。

不要太深究。

也可以以字符的形式存储啊