标签:
namespace flowlayoutpanel_容器 { public partial class picturebox : Form { public picturebox() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //从硬盘上读取图片显示在界面 openFileDialog1.Filter = "@.Jpg|*.jpg|@.Png|*.png|@.Jif|*.jif|All files|*.*"; DialogResult dr = openFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { //将图片读入流中 FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read); Image img = System.Drawing.Bitmap.FromStream(fs); //绘制 pictureBox1.Image = img; //指定 fs.Close(); } } //将图片存入到数据库 private void button2_Click(object sender, EventArgs e) { openFileDialog1.Filter = "@.Jpg|*.jpg|@.Png|*.png|@.Jif|*.jif|All files|*.*"; //存储格式 DialogResult dr = openFileDialog1.ShowDialog(); if (dr==DialogResult.OK) { FileStream fs = new FileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read ); BinaryReader br = new BinaryReader(fs); //二进制读取器 byte[] fuffer= br.ReadBytes(int.Parse (fs.Length.ToString ())); //连接数据库 SqlConnection coon = new SqlConnection("server=.;database=master;user=sa;pwd=123"); SqlCommand cmd = coon.CreateCommand(); coon.Open(); cmd.CommandText = "insert into imagetable values (@fuffer)"; cmd.Parameters.Clear(); cmd.Parameters.Add("@fuffer",fuffer ); cmd.ExecuteNonQuery(); cmd.Dispose(); coon.Close(); } } //从数据库读取图片 private void button3_Click(object sender, EventArgs e) { SqlConnection coon = new SqlConnection("server=.;database=master;user=sa;pwd=123"); SqlCommand cmd = coon.CreateCommand(); coon.Open(); cmd.CommandText = "select *from imagetable where code=7"; SqlDataReader dr = cmd.ExecuteReader(); byte[] buffer=null; if (dr.Read()) { buffer=(byte[])dr["imags"]; } coon.Close(); //将二进制buffer显示为图片 MemoryStream ms = new MemoryStream(buffer); Image img = System.Drawing.Bitmap.FromStream(ms); pictureBox1.Image = img; } } }
Windowform 窗体关联数据库存储,读取图片,参考代码
标签:
原文地址:http://www.cnblogs.com/275147378abc/p/4561196.html