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; 
}

Leave a Comment