Winform一段关于SQL存取图片的代码
需要用到
控件: openFileDialog 命名空间:using System.IO; using System.Date.SqlClient;
存
private void btnInsert_Click(object sender, EventArgs e) { openFileDialog1.Filter = "jpg图|*.jpg|png图|*.png|gif图|*.gif|所有文件|*.*"; DialogResult isok = openFileDialog1.ShowDialog(); if (isok == DialogResult.OK) { //开始使用流读取 FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read); //使用流读取器,把文件流对象中的内容读取出来,转换成字符串或者其他对应的数据 BinaryReader br = new BinaryReader(fs);//二进制读取器 byte[] imgbytes = br.ReadBytes((int)fs.Length);//将流中数据读取成byte数组存入数组变量中 //连接数据库,新增数据 SqlConnection conn = new SqlConnection("server=.;database=Practice;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "insert into Show values(@showId,@showImage)"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@showId", tboxLook.Text); cmd.Parameters.AddWithValue("@showImage", imgbytes); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show("添加水果图片成功"); } }
读取
private void btnLook_Click(object sender, EventArgs e) { //连接数据库,新增数据 SqlConnection conn = new SqlConnection("server=.;database=Practice;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select top 1 *from Show where showId=@showid"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@showId", tboxLook.Text); cmd.Parameters.AddWithValue("@showImage", tboxLook.Text); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); byte[] imgbytes = null; if (dr.Read()) { imgbytes = (byte[])dr["showImage"]; conn.Close(); //如何把二进制数据,转换成一个Image类型,来给piceturebox赋值 //内存流 MemoryStream ms = new MemoryStream(imgbytes); Image img = Image.FromStream(ms); pboxShow.Image = img; } else { MessageBox.Show("您查询的水果不存在"); } }
//纯粹为了读取硬盘的图片 private void btnChow_Click(object sender, EventArgs e) { openFileDialog1.Filter = "jpg图|*.jpg|png图|*.png|gif图|*.gif|所有文件|*.*"; DialogResult isok = openFileDialog1.ShowDialog(); if (isok == DialogResult.OK) { Image img = Image.FromFile(openFileDialog1.FileName); pboxShow.Image = img; } }