存储图片
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();//注意这一条与下两条语句的区别
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();
}
}
读取图片
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"];
ms = new (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();
}
}
---------------------------------------转