Pillow: How to detect if my image is truncated?

Created on 21 Feb 2018  路  1Comment  路  Source: python-pillow/Pillow

What did you do?

I'm using VersatileImageField and everything was working fine until we meet a jpeg file.
This file can't be rendered by VersatileImageField and we understand that VersatileImageFiled uses Pillow itlself.
By the way we are trying to determine what kind of error exists with this image and maybe this can be the
error.

This code was tested and it worked fine with a lot of other images.

What did you expect to happen?

It should render a resized image

What actually happened?

Returns the following error

The error says:

Django Version: 1.11
Exception Type: OSError
Exception Value: broken data stream when reading image file
Exception Location: C:..myenv\lib\site-packages\PIL\ImageFile.py in raise_ioerror, line 59

What versions of Pillow and Python are you using?

  • Pillow 4.3.0
  • Django 1.11
  • django-cms 3.4.5, I can't upgrade Django 1.11 by this package
  • Python 3.6.3

I trigger the error from:

<img src="{{ imagemodel.versatileimageproperty.crop.255x255 }}" srcset="{{ imagemodel.versatileimageproperty.crop.255x255 }} 1x, {{ imagemodel.versatileimageproperty.crop.255x255 }} 2x" alt="">

I was wondering if I can use the verify method to test if this image is truncated, avoid the yellow error page and show a message.

from PIL import Image
im = Image.open("C:\\absolutepathtoimage\\_DSC1318.jpg")
im.verify()

But verify returns nothing, no errors.

Question

>All comments

Image.verify is only implemented for PNG images, and it only verifies the CRC checksum in the image.

The only way to check from within Pillow is to load the image in a try/except and check the error. If you need as much info as possible from the image, you can set ImageFile.LOAD_TRUNCATED_IMAGES=True and it will attempt to parse as much as possible.

Was this page helpful?
0 / 5 - 0 ratings