[英]How can I convert System.Byte[] to Image? (C# window forms)
I have a PictureBox
control I want to display an image in it. 我有一个
PictureBox
控件我想在其中显示一个图像。 I saved my images in a MS Access database with this data type: OLE Object
. 我使用以下数据类型将我的图像保存在MS Access数据库中:
OLE Object
。 I find it hard to display it again. 我发现很难再显示它。 Please take a look at my code, and can you guys please devise a solution for it.
请看一下我的代码,你们可以为它设计一个解决方案。 I got this
Exception
: 我有这个
Exception
:
Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.
Here's my code: 这是我的代码:
OleDbCommand cmd = new OleDbCommand("SELECT IMAGE FROM IMAGES WHERE ID = 1", myConn));
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable("dt");
da.Fill(dt);
if (dt != null)
{
pictureBox1.Image = (Image)dt.Rows[0]["IMAGE"];
}
The simplest way is to use a MemoryStream
and call Image.FromStream
: 最简单的方法是使用
MemoryStream
并调用Image.FromStream
:
byte[] data = (byte[]) dt.Rows[0]["IMAGE"];
MemoryStream ms = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(ms);
EDIT: If you run up against the problem described by Hans, you basically need to strip out that header. 编辑:如果你遇到汉斯描述的问题,你基本上需要删除该标题。 Once you have got a byte array with just the image data in, use the above code.
一旦你得到了一个字节数组中带刚的图像数据,使用上面的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.