02-20 winform 上传图片并读取图片

建立一个windows窗体应用程序,在form1界面中拖入两个按钮和一个pictureBox,通过输入输出流来上传图片和显示图片。需要添加一下openFileDialog1.

界面如下:
02-20 winform 上传图片并读取图片

在cs中写上传和显示图片的方法

02-20 winform 上传图片并读取图片
 1  //上传图片
 2         private void button1_Click(object sender, EventArgs e)
 3         {
 4             //图片的转化
 5             openFileDialog1.Filter = "*jpg|*.jpg|*bmp|*.bmp|*gif|*.gif";//设置图片另存为文件类型格式,filter是文件筛选器
 6             DialogResult da = openFileDialog1.ShowDialog();
 7             if(da==DialogResult.OK)
 8             {
 9                 string fil = openFileDialog1.FileName;
10                 FileStream fs = new FileStream(fil,FileMode.Open,FileAccess.Read);
11                 byte[] img=new byte[fs.Length];
12                 BinaryReader br = new BinaryReader(fs);//二进制读取器
13                 img = br.ReadBytes(Convert.ToInt32(fs.Length));
14                 //链接数据库
15                SqlConnection conn = new SqlConnection("server=.;database=newData;user=sa;pwd=123");
16                conn.Open();
17                SqlCommand cmd = conn.CreateCommand();
18                cmd.CommandText = "insert into Table_1 values(@image)";
19                cmd.Parameters.Clear();
20                cmd.Parameters.Add("@image",img);
21                cmd.ExecuteNonQuery();
22                conn.Close();
23                MessageBox.Show("上传成功");
24 
25             }
上传图片的方法
02-20 winform 上传图片并读取图片
 1   //从数据库中读取图片
 2         private void button2_Click(object sender, EventArgs e)
 3         {
 4             SqlConnection conn = new SqlConnection("server=.;database=newData;user=sa;pwd=123");
 5             conn.Open();
 6             SqlCommand cmd = conn.CreateCommand();
 7             cmd.CommandText = "select top 1*from Table_1";
 8             SqlDataReader dr = cmd.ExecuteReader();
 9             dr.Read();
10             byte[] img = (byte[])dr["Ino"];
11            // byte[] img1=(byte[])dr["Ino"];
12             MemoryStream ms = new MemoryStream(img,0,img.Length);
13             ms.Write(img,0,img.Length);
14             Image image = Image.FromStream(ms);
15             this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
16             this.pictureBox1.Image = image;
17         }
从数据库显示图片的方法

 

02-20 winform 上传图片并读取图片

上一篇:C#关于html颜色值的转化 ColorTranslator


下一篇:visual c#设计的多功能关机程序