如何存图片到数据库中
将图片以二进制形式存入数据库时,首先要在数据库中建立一张表,将存储图片的字段类型设为Image类型,用FileStream类、BinaryReader把图片读成字节的形式,赋给一个字节数组,然后用ADO.SqlCommand对象的ExecuteNonQuery()方法来把数据保存到数据库中。主要代码如下:
1 private void button1_Clickobject sender, EventArgs e) 2 3 { 4 5 openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP"; 6 7 if(openFileDialog1.ShowDialog()==DialogResult.OK) 8 9 { 10 11 string fullpath =openFileDialog1.FileName;//文件路径 12 13 FileStream fs = new FileStream(fullpath, FileMode.Open); 14 15 byte[] imagebytes =new byte[fs.Length]; 16 17 BinaryReader br = new BinaryReader(fs); 18 19 imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length)); 20 21 //数据库连接 22 SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=db_05"); 23 24 con.Open(); 25 26 SqlCommand com = new SqlCommand("insert into tb_08 values(@ImageList)",con); 27 28 com.Parameters.Add("ImageList", SqlDbType.Image); 29 30 com.Parameters["ImageList"].Value = imagebytes; 31 32 com.ExecuteNonQuery(); 33 34 con.Close(); 35 36 } 37 38 }