Bv202
Bv202

Reputation: 4054

Image to byte array - ExternalException

I'm trying to read an image from an EID with a card reader and convert it to a byte array for database storage.

Reading the image works perfectly. I'm able to retreive a valid image with these properties: enter image description here

However, I cannot convert it to a byte array. I'm using this code, although I've tried other approaches to convert it already:

public static byte[] ImageToBytes(Image image)
{
    MemoryStream stream = new MemoryStream();
    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
    return stream.ToArray();

}

Calling the Save method gives following exception:

An exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll but was not handled in user code

The details of the exception does not clear anything up. It's a general exception with no information about what went wrong.

Any ideas what I've been doing incorrectly?

Upvotes: 2

Views: 273

Answers (1)

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34267

You might be using a wrong ImageFormat

In this documentation, it's mentioned that ExternalException will be thrown if calling .Save() with a wrong ImageFormat

you can be more generic and cover more image types if you change System.Drawing.Imaging.ImageFormat.Bmp to image.RawFormat

example:

public static byte[] ImageToBytes(Image image)
{
    MemoryStream stream = new MemoryStream();
    image.Save(stream, image.RawFormat);
    return stream.ToArray();

}

enter image description here

Upvotes: 1

Related Questions