C#图片存入数据库及其读出显示

<1>将图片转换成二进制插入数据库

        FileStream fs = new FileStream("D:\\Add.ico",FileMode.Open); 

        byte[] imagebytes = new byte[fs.Length];

        BinaryReader br = new BinaryReader(fs);

        imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));   //将图片转换成二进制字符串

        string s = "Data Source=A3135;Initial Catalog=mydb1;Integrated Security=True";  //连数据库字符串

        SqlConnection con = new SqlConnection(s);

        con.Open();

        string str = " insert into [picture](Line,Data) values(@Line,@Data)";  //插入picture表中字符串

        SqlCommand cmd = new SqlCommand(str, con);

        cmd.Parameters.AddWithValue("@Line", 1);

        cmd.Parameters.AddWithValue("@Data", imagebytes);  //将二进制流插入数据库中

        cmd.ExecuteNonQuery();

        con.Close();

<2>将二进制还原为图片

     MemoryStream ms = new MemoryStream(photo);

     Bitmap bmpt = new Bitmap(ms);   //将二进制流转化成图片格式

     SickPicture.Image = bmpt;   //SickPicture为pictureBox控件名称

<3>依据图片路径显示图片

      Image image = Image.FromFile(PicturePath);  //直接打开会出现再次添加时提示图片资源占用

      Image bmp = new Bitmap(image);

      SickPicture.Image = bmp;

      image.Dispose();

<4>PictureBox绑定图片的等比缩放

      将pictureBox的SizeMode属性设置为StretchImage

posted @ 2015-08-27 00:25  best.lei  阅读(1237)  评论(0编辑  收藏  举报