gpt4 book ai didi

c# - 显示从 db 到 picturebox winforms c# 的图像

转载 作者:太空宇宙 更新时间:2023-11-03 15:58:34 25 4
gpt4 key购买 nike

我正在做一个 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);

}

}

最佳答案

首先你必须考虑你的图像数据库中的数据类型必须是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);
}

关于c# - 显示从 db 到 picturebox winforms c# 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com