C# 从db到picturebox WinC窗体显示图像#
我正在使用winforms应用程序将图像插入数据库(sql server 2008),并将图像从数据库检索到图片框中。插入的代码工作正常。虽然检索显示的代码出现错误,但参数无效。我尝试了通过目测找到的各种解决方案,但均未成功 这是我的检索代码C# 从db到picturebox WinC窗体显示图像#,c#,sql,winforms,C#,Sql,Winforms,我正在使用winforms应用程序将图像插入数据库(sql server 2008),并将图像从数据库检索到图片框中。插入的代码工作正常。虽然检索显示的代码出现错误,但参数无效。我尝试了通过目测找到的各种解决方案,但均未成功 这是我的检索代码 private void button2_Click(object sender, EventArgs e) { FileStream fs1 = new FileStream("D:\\4usdata.tx
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);
}
}
请尝试以下代码:
要存储到数据库中,请执行以下操作:
public byte[] WinImage=new byte[0];
MemoryStream stream = new MemoryStream();
PictureBox.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
WinImage=stream.ToArray();
MemoryStream stream = new MemoryStream(byte[] WinImage);
Image RetImage = Image.FromStream(stream);
PictureBox.Image = RetImage;
并将其作为varbinary(max)保存到表中
要从数据库检索图像,请执行以下操作:
public byte[] WinImage=new byte[0];
MemoryStream stream = new MemoryStream();
PictureBox.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
WinImage=stream.ToArray();
MemoryStream stream = new MemoryStream(byte[] WinImage);
Image RetImage = Image.FromStream(stream);
PictureBox.Image = RetImage;
您可以这样做,
Byte[] MyData = new byte[0];
MyData = (Byte[])ds.Tables[0].Rows[0]["img"];
if (MyData != null && MyData .Length > 0)
{
string img = Convert.ToBase64String(MyData , 0, MyData.Length);
pictureBox1.ImageUrl = "data:image/png;base64," + img;
}
首先,您必须考虑图像数据库中的数据类型必须是ValBoo: < /P> 在按钮单击事件中:
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);
}
数据库中的
img
字段的类型是什么?@RagingBull img字段是图像类型何时处理stream
?当我在设置PictureBox.Image=Image.FromStream(stream)之后尝试处理它时,我得到一个ObjectDisposedException。让小溪无限期地流淌似乎不明智。