在c#.net应用程序中将图像从数据库检索到窗体表单时出错 [英] error in retrievng image from database to windows form in c# .net application
问题描述
调试下面的代码时出错了。错误是参数无效。请任何人建议解决方案
代码是
when debugging the below code i got an error. The error is parameter is not valid. Pls anyone suggest a solution
the code is
cn.copen();
SqlDataAdapter adt = new SqlDataAdapter("select image from reg where studentid='" + cmbstdid.Text + "' ", cn.con);
DataSet ds1 = new DataSet();
adt.Fill(ds1);
cn.cclose();
if (ds1.Tables[0].Rows.Count > 0)
{
byte[] imageData = (byte[])ds1.Tables[0].Rows[0]["image"];
Image newImage;
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
ms.Write(imageData, 0, imageData.Length);
newImage = Image.FromStream(ms, true);
//error is shown in the above line
}
pictureBox1.Image = newImage;
pic = ds1.Tables[0].Rows[0]["image"].ToString();
}
已添加代码块[/编辑]
Code block added[/Edit]
推荐答案
您好,< br $>
你必须将MemoryStream
的位置设置为0
:
Hi,
You have to set the position of theMemoryStream
to0
:
ms.Write(imageData, 0, imageData.Length);
ms.Seek(0, SeekOrigin.Begin); // Add this line. The Seek method sets the position of the Stream to 0
newImage = Image.FromStream(ms, true);
如果你得到同样的错误,试试
If you get the same error, try
ms.Write(imageData, 0, imageData.Length);
ms.Seek(0, SeekOrigin.Begin);
newImage = Image.FromStream(ms);
如果再次出现同样的错误,请尝试
And if you get the same error again, try
ms.Write(imageData, 0, imageData.Length);
ms.Seek(0, SeekOrigin.Begin);
newImage = (Image)new Bitmap(ms);
根据您的评论,您只保存图像的文件名,而不是图像本身。要了解如何将图像存储到数据库中,请阅读以下文章:使用Strored过程和C#.net 从SQL Server存储和检索图像[ ^ ]
希望这有帮助。
According to your comment, you only save the file name of the image, not the image itself. To learn how to store an image into a database, read this article: Storing and Retrieving Images from SQL Server Using Strored Procedures and C#.net[^]
Hope this helps.
您好,
使用以下代码。这完美无缺。
Hi,
Use the below code.This works perfectly.
if (ds1.Tables[0].Rows.Count > 0)
{
{
if(ds1.Tables[0].Rows[0]!=DBNull.Value)
{
byte[] imageData = (byte[])ds1.Tables[0].Rows[0]["image"]
}
MemoryStream ms=new MemoryStreamm(imageData);
pictureBox1.Image = Image.FromStream(ms);
}
else
pictureBox1.Image=null;
}
}
这篇关于在c#.net应用程序中将图像从数据库检索到窗体表单时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!