Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine in Python (or other language) to see if a JPG image is corrupt?

Tags:

python

file

image

I was wondering if there was a way to determine in Python (or another language) to open a JPEG file, and determine whether or not it is corrupt (for instance, if I terminate a download for a JPG file before it completes, then I am unable to open the file and view it)? Are there libraries that allow this to be done easily?

like image 448
Raymond Avatar asked Aug 21 '12 08:08

Raymond


People also ask

How can I tell if a file is JPEG?

If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.


1 Answers

You can try using PIL. But just opening a truncated JPG file won't fail, and neither will the verify method. Trying to load it will raise an exception, though;

First we mangle a good jpg file:

> du mvc-002f.jpg
56  mvc-002f.jpg
> dd if=mvc-002f.jpg of=broken.jpg bs=1k count=20
20+0 records in
20+0 records out
20480 bytes transferred in 0.000133 secs (154217856 bytes/sec)

Then we try the Python Imaging Library:

>>> import Image
>>> im = Image.open('broken.jpg')
>>> im.verify()
>>> im = Image.open('broken.jpg')  # im.verify() invalidates the file pointer
>>> im.load()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/PIL/ImageFile.py", line 201, in load
    raise IOError("image file is truncated (%d bytes not processed)" % len(b))
IOError: image file is truncated (16 bytes not processed)

As user827992 said, even a truncated image can usually still be partially decoded and shown.

like image 114
Roland Smith Avatar answered Nov 01 '22 11:11

Roland Smith