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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With