【发布时间】:2012-11-15 04:20:35
【问题描述】:
您好,我正在尝试从数据库中获取字节数组并将其转换为可用于在我的 .aspx 页面中显示来自数据库的图像的内容。我使用的是严格的 c#。
这是我的代码。
SqlCommand picCommand = connection.CreateCommand();
picCommand.CommandText = ("SELECT ItemImage FROM Inventory WHERE ItemName = '" + DropDownList1.SelectedItem.Text + "';");
connection.Open();
object returnPic;
returnPic = picCommand.ExecuteScalar();//value that is read as the byte array or intended to be read as byte array.
connection.Close();
UTF8Encoding utf8 = new UTF8Encoding();
//where i intend to convert the
byte[] image = utf8.GetBytes(returnPic.ToString());
System.Drawing.Image myImage;
using (MemoryStream inStream = new MemoryStream())
{
inStream.Write(image, 0, image.Length);
myImage = Bitmap.FromStream(inStream);
}
this.ItemImageBox.Equals(myImage);
代码编译并运行,但是当它到达执行该行的位置时 myImage = Bitmap.FromStream(instream) 我收到此错误 System.ArgumentException:参数无效。实际上,我是通过查看各种不同的来源获得了这段代码,所以也许这里的人可以告诉我我是否做错了什么。
先谢谢了!
【问题讨论】:
-
这就是你需要的:
Image.FromStream(new MemoryStream((byte[])picCommand.ExecuteScalar())); -
考虑重构你的 SQL 语句,这样你就可以避免诸如 Sql Injection 之类的事情。Dave 也有很好的建议
-
将图像编码为 utf-8 是非常不太可能取得好的结果。 utf-8只能编码文本,不适合编码二进制数据。