将图片转换成二进制的形式存储到数据库
首先,在sql数据库中建立一个表,有两个字段:ID、Image,其中ID为主键,Image的存储类型为Image类型。
1)、实现图片存储:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter="*.jpg|*.JPG";//设置弹出对话框选择图片
openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string path = openFileDialog1.FileName;
using (FileStream filestream = new FileStream(path, FileMode.Open))
{
Byte[] imageByte = new byte[filestream.Length];
filestream.Read(imageByte,0,imageByte.Length);//将图片数据读入比特数组存储
string connectionstring = "Data Source=(local);Initial Catalog=Test;Integrated Security=SSPI";
SqlConnection sqlcon = new SqlConnection(connectionstring);
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand("insert into Image(ID,Image) values (1,@ImageList)",sqlcon);//此处设置一个占位符ImageList,含义将在以下定义
sqlcom.Parameters.Add("ImageList",SqlDbType.Image);
sqlcom.Parameters["ImageList"].Value = imageByte;
sqlcom.ExecuteNonQuery();
sqlcon.Close();
}
}
}
2)、实现图片的提取:
private void button2_Click(object sender, EventArgs e)
{
string connectionstring = "Data Source=(local);Initial Catalog=Test;Integrated Security=SSPI";
SqlConnection sqlcon = new SqlConnection(connectionstring);
sqlcon.Open();
byte[] imagebytes;
SqlCommand sqlcom = new SqlCommand("select Image from Image where ID=1",sqlcon);//查询到要提取的图片
SqlDataReader dr = sqlcom.ExecuteReader();
if (dr.Read())
{
imagebytes = (byte[])dr["Image"];
MemoryStream ms = new MemoryStream(imagebytes);//创建图片数据流
Bitmap bmap = new Bitmap(ms);//获取图片
ms.Close();
pictureBox1.Image = bmap;
}
}