I get a byte stream from some web service. This byte stream contains the binary date of an image and I\'m using the method below to convert it to an Image instance.
Parsing a byte array into an actual image object can be resource intensive especially for huge amounts of data
You can use Magic Numbers instead
JPEG image files begin with FF D8 and end with FF D9
...
PNG image files begin with an 8-byte signature which identifies the file as a PNG file and allows detection of common file transfer problems: (89 50 4E 47 0D 0A 1A 0A)
etc.
Some example code for you:
public bool IsPng(byte[] array)
{
return array != null
&& array.Length > 8
&& array[0] == 0x89
&& array[1] == 0x50
&& array[2] == 0x4e
&& array[3] == 0x47
&& array[4] == 0x0d
&& array[5] == 0x0a
&& array[6] == 0x1a
&& array[7] == 0x0a
}
Of course, you should further validate the data after this quick check to be 100% sure the format is safe and is an actual image.
P.S. this is how browsers do it