小编典典

从db显示图片到Picturebox WinForms C#

sql

我正在做一个winforms应用程序,将图像插入数据库(SQL Server
2008),然后从数据库中检索图像到图片框。插入代码可以完美地工作。尝试通过窥视找到各种解决方案,但没有一个成功。

这是我的检索代码

           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);

        }

    }

阅读 173

收藏
2021-05-30

共1个答案

小编典典

首先,您必须考虑图像数据库中的数据类型必须为VarBinary:

在您的按钮点击事件中:

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);
}
2021-05-30