2

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?

Bv202
  • 3,924
  • 13
  • 46
  • 80

1 Answers1

1

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

Community
  • 1
  • 1
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129