1、先在Form中放一个PictureBox控件,再放三个按钮。
2、双击打开按钮,在里面写如下代码:
OpenFileDialog open1 = new OpenFileDialog();
DialogResult isok = open1.ShowDialog();
if (isok == DialogResult.OK)
{
string filename = open1.FileName;
FileStream fs = new FileStream(filename,FileMode.Open);
Image img = Image.FromStream(fs);
pictureBox1.Image = img;
fs.Close();
}
3、双击存储到数据库按钮,在里面写如下代码:
OpenFileDialog open1 = new OpenFileDialog();
DialogResult isok = open1.ShowDialog();
if (isok == DialogResult.OK)
{
//根据路径读取图片,把图片存到数据库
string filename = open1.FileName;
FileStream fs = new FileStream(filename, FileMode.Open);
BinaryReader br = new BinaryReader(fs);//二进制读取器
byte[] buffer = br.ReadBytes((int)fs.Length);//图片数据进去到buffer中
br.Close();
fs.Close();
SqlConnection conn = new SqlConnection("server=.;database=图片;user=sa;pwd=123");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "insert into tupian values(@image)";
cmd.Parameters.Clear();
cmd.Parameters.Add("@image", buffer);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
4、双击读取数据库按钮,在里面写如下代码:
SqlConnection conn = new SqlConnection("server=.;database=图片;user=sa;pwd=123");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select *from tupian where id=1";
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
byte[] buffer = (byte[])dr["image"];
MemoryStream ms = new MemoryStream(buffer);
Image img = Image.FromStream(ms);
pictureBox1.Image = img;
}
conn.Close();