我怎么能转换System.Byte []到图像? (C#窗口形式) [英] How can I convert System.Byte[] to Image? (C# window forms)
问题描述
我有一个图片框
控制我想它来显示图像。我用这种数据类型保存我的图片在MS Access数据库: OLE对象
。
我觉得很难再次显示。请看看我的代码,并可以你们,请设计为它的解决方案。我得到这个例外
:
无法投类型的对象'系统.BYTE []'键入'System.Drawing.Image对象。
下面是我的代码:
CMD的OleDbCommand =新的OleDbCommand(选择映像从图像WHERE ID = 1,的myconn));
cmd.CommandType = CommandType.Text;
OleDbDataAdapter的DA =新OleDbDataAdapter的(CMD);
DataTable的DT =新的DataTable(DT);
da.Fill(DT);
如果(DT!= NULL)
{
pictureBox1.Image =(图)dt.Rows [0] [形象];
}
最简单的方法是使用一个的MemoryStream
和呼叫 Image.FromStream
:
字节[]数据=(字节[])dt.Rows [0] [形象];
的MemoryStream毫秒=新的MemoryStream(数据);
pictureBox1.Image = Image.FromStream(毫秒);
编辑:如果你反对汉斯描述的问题跑起来,你基本上需要去掉该头。一旦你的有无的有中带刚,使用上面的代码中的图像数据的字节数组。
I have a PictureBox
control I want to display an image in it. I saved my images in a MS Access database with this data type: 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
:
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
:
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.
这篇关于我怎么能转换System.Byte []到图像? (C#窗口形式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!