基于winform的二进制图片数据的存取(用于数据库照片的读写处理)

编程目的:文本框1中输入id号,则从openFileDialog中选择的图片会以二进制数据存进SQL数据库的对应表的id列;文本框2中输入姓名,从数据库读取对应name的照片并显示在pictureBox控件上。

预备操作:新建一个sql数据库,包含一个拥有id和name,image的表,如下图所示,窗体中拖拽两个文本框和两个button按钮。

基于winform的二进制图片数据的存取(用于数据库照片的读写处理)

1、主功能类

  public void SaveImage(string ID,OpenFileDialog openF)  //openFileDialog打开的图片以二进制流的方式存到数据库的指定表的指定id号的记录中
{
string P_str = openF.FileName;
FileStream fs = new FileStream(P_str,FileMode.Open,FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] imageBytesIn = br.ReadBytes((int)fs.Length);
SqlConnection conn = BaseClass.DBConn.CyCon();
conn.Open();
StringBuilder strSql = new StringBuilder();
strSql.Append("update test_photo set photo=@Photo where id="+ID);
SqlCommand cmd = new SqlCommand(strSql.ToString(),conn);
cmd.Parameters.Add("@Photo",SqlDbType.Binary).Value=imageBytesIn;
cmd.ExecuteNonQuery();
conn.Close();
} public void Get_Image(string yname,PictureBox pb)//从数据库中读取指定姓名的二进制数据图片并显示
{ byte[]imagebytes=null;
SqlConnection conn = BaseClass.DBConn.CyCon();
conn.Open();
SqlCommand com=new SqlCommand("select * from test_photo where name='"+yname+"'",conn);
SqlDataReader dr=com.ExecuteReader();
while(dr.Read())
{imagebytes=(byte[])dr.GetValue(1);}
dr.Close();
conn.Close();
MemoryStream ms=new MemoryStream(imagebytes);
Bitmap bmpt = new Bitmap(ms);
pb.Image = bmpt; }

2、调用类

  bll b = new bll();

        private void btnSavePhotoToDB_Click(object sender, EventArgs e)
{ if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
b.SaveImage(textBox1.Text, openFileDialog1); } MessageBox.Show("存照片成功");//支持bmp,jpg,gif
} private void btnShowPhotoFromDB_Click(object sender, EventArgs e)
{
b.Get_Image(textBox2.Text, pictureBox1);
}

3、运行效果图

基于winform的二进制图片数据的存取(用于数据库照片的读写处理)
上一篇:myeclipse ctrl + 鼠标单击 出现 source not found


下一篇:java_JDBC(2)