将图像从数据库显示到图片框 winforms c# [英] Displaying image from db to picturebox winforms c#

查看:24
本文介绍了将图像从数据库显示到图片框 winforms c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个 winforms 应用程序,将图像插入数据库(sql server 2008)并将图像从数据库中检索到图片框中.插入代码完美无缺.虽然检索代码显示错误参数无效.我尝试了通过护目镜找到的各种解决方案,但没有一个成功.

Iam doing a winforms application to insert an image to a database(sql server 2008)and retrieve an image from database into a picture box.The code for inserting works perfectly.While the code for retrieving show's up an error parameter not Valid.I was trying various solutions found by goggling but none of them succeeded.

这是我的检索代码

           private void button2_Click(object sender, EventArgs e)
            {
 FileStream fs1 = new FileStream("D:\\4usdata.txt", FileMode.OpenOrCreate,FileAccess.Read);
        StreamReader reader = new StreamReader(fs1);
        string id = reader.ReadToEnd();
        reader.Close();
        int ide = int.Parse(id);
        con.Open();
        SqlCommand cmd = new SqlCommand("select img from tempdb where id='" + id + "'", con);
        //cmd.CommandType = CommandType.Text;
        //object ima = cmd.ExecuteScalar();
        //Stream str = new MemoryStream((byte[])ima);
        //pictureBox1.Image = Bitmap.FromStream(str);
        SqlDataAdapter dp = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        dp.Fill(ds);
        int c = ds.Tables[0].Rows.Count;
        if (c ==1)
        {


            Byte[] MyData = new byte[0];
            MyData = (Byte[])ds.Tables[0].Rows[0]["img"];
            MemoryStream stream = new MemoryStream(MyData);
            stream.Position = 0;
            pictureBox1.Image = Image.FromStream(stream);

        }

    }

推荐答案

首先你必须考虑到你的图像数据库中的数据类型必须是 VarBinary:

First you must consider that the datatype in your Database of image must be VarBinary:

在您的按钮点击事件中:

in your button click event:

byte[] getImg=new byte[0];
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select img from tempdb where id='" + id + "'", con);
cmd.CommandType=CommandType.Text;
DataSet ds = new DataSet();
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
   getImg=(byte[])dr["img"];
}

byte[] imgData=getImg;
MemoryStream stream = new MemoryStream(imgData);
pictureBox1.Image=Image.FromStream(stream);
}

这篇关于将图像从数据库显示到图片框 winforms c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆