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

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

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

  //上传图片
private void button1_Click(object sender, EventArgs e)
{
//图片的转化
openFileDialog1.Filter = "*jpg|*.jpg|*bmp|*.bmp|*gif|*.gif";//设置图片另存为文件类型格式,filter是文件筛选器
DialogResult da = openFileDialog1.ShowDialog();
if(da==DialogResult.OK)
{
string fil = openFileDialog1.FileName;
FileStream fs = new FileStream(fil,FileMode.Open,FileAccess.Read);
byte[] img=new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);//二进制读取器
img = br.ReadBytes(Convert.ToInt32(fs.Length));
//链接数据库
SqlConnection conn = new SqlConnection("server=.;database=newData;user=sa;pwd=123");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "insert into Table_1 values(@image)";
cmd.Parameters.Clear();
cmd.Parameters.Add("@image",img);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("上传成功"); }

上传图片的方法

   //从数据库中读取图片
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("server=.;database=newData;user=sa;pwd=123");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select top 1*from Table_1";
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
byte[] img = (byte[])dr["Ino"];
// byte[] img1=(byte[])dr["Ino"];
MemoryStream ms = new MemoryStream(img,,img.Length);
ms.Write(img,,img.Length);
Image image = Image.FromStream(ms);
this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
this.pictureBox1.Image = image;
}

从数据库显示图片的方法

04-15 22:18
查看更多