Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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"];
            }
like image 477
yonan2236 Avatar asked Aug 09 '10 13:08

yonan2236


1 Answers

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.

like image 100
Jon Skeet Avatar answered Sep 22 '22 05:09

Jon Skeet