8

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"];
            }
yonan2236
  • 13,371
  • 33
  • 95
  • 141

1 Answers1

28

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • But i dont fine PictureBox Option ?? please help – SanamShaikh Jun 12 '15 at 19:12
  • @Sanam: I don't know what you mean. In the context of the question, the OP has a pictureBox1 variable. I have no idea what you're trying to do or your context. I suggest you ask a new question. – Jon Skeet Jun 12 '15 at 19:22
  • Shouldn't we surround `MemoryStream` by `using` or at least dispose the instance after setting the control image? – Ghasem Dec 31 '15 at 08:22
  • 1
    @AlexJolig: You *mustn't* dispose of it - `Image.FromStream` assumes ownership of the stream. DIsposing of the image will dispose of the stream, but for a `MemoryStream` it doesn't matter anyway. – Jon Skeet Dec 31 '15 at 09:08