[ACCEPTED]-How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted?-image

Accepted answer
Score: 27

An easy way would be to try loading and 2 verifying the files with PIL (Python Imaging 1 Library).

from PIL import Image

v_image = Image.open(file)

Catch the exceptions...

From the documentation:


Attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. This method only works on a newly opened image; if the image has already been loaded, the result is undefined. Also, if you need to load the image after using this method, you must reopen the image file.

Score: 7

i suggest you check out imagemagick for 4 this: http://www.imagemagick.org/

there you have a tool called identify 3 which you can either use in combination 2 with a script/stdout or you can use the 1 programming interface provided

Score: 5

In PHP, with exif_imagetype():

if (exif_imagetype($filename) === false)
    unlink($filename); // image is corrupted

EDIT: Or you can try to fully 4 load the image with ImageCreateFromString():

if (ImageCreateFromString(file_get_contents($filename)) === false)
    unlink($filename); // image is corrupted

An image resource will 3 be returned on success. FALSE is returned if the image type 2 is unsupported, the data is not in a recognized 1 format, or the image is corrupt and cannot be loaded.

Score: 3

If your exact requirements are that it show 23 correctly in FireFox you may have a difficult time 22 - the only way to be sure would be to link 21 to the exact same image loading source code 20 as FireFox.

Basic image corruption (file 19 is incomplete) can be detected simply by 18 trying to open the file using any number 17 of image libraries.

However many images can 16 fail to display simply because they stretch 15 a part of the file format that the particular 14 viewer you are using can't handle (GIF in 13 particular has a lot of these edge cases, but 12 you can find JPEG and the rare PNG file 11 that can only be displayed in specific viewers). There 10 are also some ugly JPEG edge cases where 9 the file appears to be uncorrupted in viewer X, but 8 in reality the file has been cut short and 7 is only displaying correctly because very 6 little information has been lost (FireFox 5 can show some cut off JPEGs correctly [you 4 get a grey bottom], but others result in 3 FireFox seeming the load them half way and 2 then display the error message instead of 1 the partial image)

Score: 0

You could use imagemagick if it is available:

if 2 you want to do a whole folder

identify "./myfolder/*" >log.txt 2>&1

if you want 1 to just check a file:

identify myfile.jpg

More Related questions