简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM