6

I'm trying to load my .jpg file and it raises error, but if I try it again, it's ok! Why??

My code and error:

>>> import Image
>>> im1 = Image.open('/tmp/test.jpg')
>>> im1.load()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/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 (0 bytes not processed)
>>> im1.load()
<PixelAccess object at 0x7feffc2a1170>
>>>

Thank you!

Hare
  • 71
  • 1
  • 1
  • 3
  • The message suggests the image you're tying to load is (probably) missing some trailing bytes. Why does it work intermitently, I don't know, as you don't say if the image is static, etc. – Ricardo Cárdenes Feb 09 '12 at 13:41
  • Thank you for the answer! The image is static. – Hare Feb 09 '12 at 15:20

2 Answers2

20

I had this same issue and came up with a solution which I discuss here: https://stackoverflow.com/a/23575424/3622198.

Somewhere before your code block, simply add the following:

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

... and you should be good to go!

EDIT: It looks like this helps for the version of PIL bundled with Pillow ("pip install pillow"), but may not work for default installations of PIL

Community
  • 1
  • 1
abhillman
  • 3,942
  • 1
  • 20
  • 21
8

PIL uses lazy loading, which means the image isn't actually read from the file until you try to perform an action on it. The first call to load is that first action, so that's when the problem with the file format is detected. The second call to load doesn't read the file again, it just returns information that was cached when the file was loaded.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Heh... Only now I noticed that the second call to `load` mentioned by OP was in the example... – Ricardo Cárdenes Feb 09 '12 at 16:44
  • Hm, sorry, I haven't told that the similar error happens when the first call is image.show. A second call image.show is ок. – Hare Feb 09 '12 at 17:44
  • @Hare, the same reasoning applies. The `open` request doesn't read the entire file so it doesn't get the error. The first operation whether it's `load` or `show` causes the entire file to be read, and the file defect is detected. – Mark Ransom Feb 09 '12 at 18:27