How to check if a byte array is a valid image? How to check if a byte array is a valid image? arrays arrays

How to check if a byte array is a valid image?


You can try to generate an image from the byte array and check for the ArgumentException if its not.

public static bool IsValidImage(byte[] bytes){    try {        using(MemoryStream ms = new MemoryStream(bytes))           Image.FromStream(ms);    }    catch (ArgumentException) {       return false;    }    return true; }


As noted, trying to load it into an image is the only fail-safe way. You can check the magick number aka file header based on the [expected] image type. For instance, the first 8 octets of a *.PNG file are, in hex:

0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A

http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header

Most other types of image files have similar magick numbers.

But checking that won't actually tell you if the file is a valid image file. All you'll know after that is that the magick number seems to indicate that its a file of type X. It could still be truncated or otherwise corrupted, or even be something else entirely that just happens to have the right sequence of octets in the right place.


For a JPEG you can check that the first two bytes are 0xFF, 0xD8 and the last two are 0xFF, 0xD9. Of course its still possible that the image data will match the EOI tag, but this should be rare.