按:在某些情况下,项目要求将图片以二进制形式存入数据库中,这与将图片的链接存入数据库是不同的。本段代码使用C#实现了图片到SQL SERVER 2005数据库的存取的功能。值得注意的是,图片与数据流的转换,数据流与二进制的转换,任何一次的转换稍有问题,都有可能导致存储或者读取的数据出现问题。在存储部分的代码中,有两条语句(已注释),貌似实现了数据流到二进制的转换,也能够存入数据库,但读取的时候会发现数据会有问题。
特别说明:本文的代码并非原创,是对网络资源的搜集、整理和修改而成。
- //这一段代码实现从SQL Server 2005数据库读取图片的二进制内容,再在窗体上的image控件pictureBox1上显示出来。
- private void btnReadPicture_Click(object sender, EventArgs e)
- {
- //使用use关键字可以不在连接字符串中指定数据库名字
- SqlConnection conn = new SqlConnection("Data Source=.;Integrated Security=True");
- conn.Open();
- string strSql = "use Northwind select Picture from Pictures where id = 4";
- SqlCommand com = new SqlCommand(strSql, conn);
- SqlDataReader dr = com.ExecuteReader();
- try
- {
- dr.Read();
- byte[] btImage = (byte[])dr["Picture"];
- System.IO.MemoryStream ms = new System.IO.MemoryStream(btImage);
- System.Drawing.Image image = System.Drawing.Image.FromStream(ms);//将二进制转换为流
- //Bitmap image = new Bitmap(ms);//用这条替换上一条也是可以的
- pictureBox1.Image = image;
- }
- catch (Exception ee)
- {
- MessageBox.Show(ee.Message);
- }
- finally
- {
- conn.Close();
- dr.Close();
- }
- }
- //下面的代码实现图片以二进制形式存储到SQL Server 2005数据库。图片来源于窗体上的Image控件pictureBox2。
- private void btnSavePicture_Click(object sender, EventArgs e)
- {
- Image Picture = this.pictureBox2.Image;//获取图片
- MemoryStream ms = new MemoryStream();
- Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//转换成数据流
- byte[] bPicture = ms.GetBuffer();//注意这一条与下两条语句的区别
- //下面这两条语句似乎要实现存储二进制的目的,但存储图片的方式会有问题,读出来的数据无法还原成图片
- //byte[] bPicture = new byte[ms.Length];
- //ms.Write(bPicture, 0, (int)ms.Length);
- SqlConnection conn = new SqlConnection("Data Source=.;Integrated Security=True");
- string strSQL = "use Northwind Insert into Pictures(Picture) values(@image)";
- SqlCommand cmd = new SqlCommand(strSQL, conn);
- cmd.Parameters.Add("@image", SqlDbType.Image);
- cmd.Parameters["@image"].Value = bPicture;
- try
- {
- conn.Open();
- cmd.ExecuteNonQuery();
- MessageBox.Show("存储成功!");
- }
- catch (Exception ee)
- {
- MessageBox.Show(ee.Message);
- }
- finally
- {
- conn.Close();
- }
- }