//浏览图片 private void btnUp_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "选择要上传的图片"; ofd.Filter = "All Files(*.*)|*.*|位图(*.bmp)|*.bmp|JPEG(*.jpg)|*.jpg"; ofd.ShowDialog(); textBox1.Text = ofd.FileName; if (!File.Exists(ofd.FileName)) { MessageBox.Show("照片为空"); return; } } //上传保存到数据库 private void btnUpLoad_Click(object sender, EventArgs e) { string strPath = txtbImage.Text.Trim(); FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.Read); byte[] byteFile = new byte[fs.Length]; fs.Read(byteFile, , (int)fs.Length); fs.Close(); SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True"); try { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; string strSql = "insert into test(FileName,Img) Values(@FileName,@Img)"; cmd.CommandText =strSql ; //cmd.Parameters.AddWithValue("@FileName", strPath); //cmd.Parameters.AddWithValue("@Img", byteFile); //或者 SqlParameter[] parameters = new SqlParameter[]; parameters[] = new SqlParameter("@FileName", SqlDbType.NVarChar, ); parameters[].Value = strPath; parameters[] = new SqlParameter("@Img", SqlDbType.Image,int.MaxValue); parameters[].Value = byteFile; cmd.Parameters.AddRange(parameters); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show("上传成功"); } catch { conn.Close(); MessageBox.Show("上传失败!"); } } 从数据库读取图片显示到窗体: //读到图片显示到PictureBox private void btnDownLoad_Click(object sender, EventArgs e) { byte[] bytFile; SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True"); try { SqlCommand cmd = new SqlCommand(); string strSql = "select img from test where ID=3"; cmd.Connection = conn; cmd.CommandText = strSql; conn.Open(); SqlDataReader sdr = cmd.ExecuteReader(); if (sdr.Read()) { bytFile = (Byte[])sdr["Img"]; } else { bytFile = new byte[]; } sdr.Close(); conn.Close(); //通过内存流MemoryStream, //把byte[]数组fileContent加载到Image中并赋值给图片框的Image属性, //让数据库中的图片直接显示在窗体上。 MemoryStream ms = new MemoryStream(bytFile, , bytFile.Length); this.picImage.Image = Image.FromStream(ms); //关闭内存流 ms.Close(); } catch { conn.Close(); MessageBox.Show("失败"); } }
代码转自IT学习广场http://www.itxxgc.com/net/detail/30
来自凌波小屋-----冯和超的笔记-------