7

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!

2
  • 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. Commented Feb 9, 2012 at 13:41
  • Thank you for the answer! The image is static. Commented Feb 9, 2012 at 15:20

2 Answers 2

21

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Heh... Only now I noticed that the second call to load mentioned by OP was in the example...
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, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.