开发者

How can I convert System.Byte[] to Image? (C# window forms)

I have a PictureBox control I want to display an image in it. I saved my images in a MS Acce开发者_如何学运维ss 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜