图片导入导出数据库

 1         private Stream stream=new Stream();
 2         Bitmap bp=new Bitmap();
 3         /// <summary>
 4         /// 向数据库中导入图片
 5         /// </summary>
 6         /// <param name="sender"></param>
 7         /// <param name="e"></param>
 8         private void button1_Click(object sender, EventArgs e)
 9         {
10             OpenFileDialog of = new OpenFileDialog();
11             if (of.ShowDialog() == DialogResult.OK)
12             {
13                 bp = new Bitmap(of.FileName);
14                 stream=of.OpenFile();//2下面
15 } 16 string sql = "update h_doctor set xiangPian=?xiangpian where ID="+12; 17 using (MySqlConnection conn = new MySqlConnection(mysqlHelp.ConnectionString)) 18 { 19 MySqlCommand cmd = new MySqlCommand(sql, conn); 20 byte[] bytes = new byte[stream.Length]; 21 stream.Read(bytes, 0, (int)stream.Length); 22 cmd.Parameters.AddWithValue("?xiangpian", bytes); 23 try 24 { 25 conn.Open(); 26 cmd.ExecuteNonQuery(); 27 pictureBox1.Image = bp; 28 } 29 catch (Exception e1) 30 { 31 MessageBox.Show("图片太大!图片支持20K以内"); 32 } 33 finally 34 { 35 conn.Close(); 36 } 37 38 } 39 40 } 41 /// <summary> 42 /// 图片导出 43 /// </summary> 44 /// <param name="sender"></param> 45 /// <param name="e"></param> 46 private void button2_Click(object sender, EventArgs e) 47 { 48 string sql = "select xiangpian from h_doctor where ID=" + 12; 49 using (MySqlConnection conn = new MySqlConnection(mysqlHelp.ConnectionString)) 50 { 51 MySqlCommand cmd = new MySqlCommand(sql, conn); 52 conn.Open(); 53 MySqlDataReader read = cmd.ExecuteReader(); 54 if (read.Read()) 55 { 56 if (read[0].GetType() != typeof(DBNull)) 57 { 58 byte[] bs = (byte[])read[0]; 59 MemoryStream mem = new MemoryStream(bs); 60 Bitmap bm = new Bitmap(mem); 61 pictureBox1.Image = bm; 62 } 63 } 64 } 65 }

2、 FileStream fs = File.OpenRead(of.FileName));
            byte[] imageb = new byte[fs.Length];
            fs.Read(imageb, 0, imageb.Length);
            fs.Close();
            SqlCommand com3 = new SqlCommand (sql,con);
            com3.Parameters.Add("@images", SqlDbType.Image).Value = imageb;

原文地址:https://www.cnblogs.com/zhao123/p/3357867.html