Skip to content Skip to sidebar Skip to footer

Django PIL : IOError Cannot Identify Image File

I'm learning Python and Django. An image is provided by the user using forms.ImageField(). Then I have to process it in order to create two different sized images. When I submit th

Solution 1:

As ilvar asks in the comments, what kind of object is image? I'm going to assume for the purposes of this answer that it's the file property of a Django ImageField that comes from a file uploaded by a remote user.

After a file upload, the object you get in the ImageField.file property is a TemporaryUploadedFile object that might represent a file on disk or in memory, depending on how large the upload was. This object behaves much like a normal Python file object, so after you have read it once (to make the first thumbnail), you have reached the end of the file, so that when you try to read it again (to make the second thumbnail), there's nothing there, hence the IOError. To make a second thumbnail, you need to seek back to the beginning of the file. So you could add the line

image.seek(0)

to the start of your image_resizer function.

But this is unnecessary! You have this problem because you are asking the Python Imaging Library to re-read the image for each new thumbnail you want to create. This is a waste of time: better to read the image just once and then create all the thumbnails you want.


Solution 2:

I'm guessing that is a TemporaryUploadedFile ... find this with type(image).

import cStringIO

if isinstance(image, TemporaryUploadedFile):
    temp_file = open(image.temporary_file_path(), 'rb+')
    content = cStringIO.StringIO(temp_file.read())
    image = Image.open(content)
    temp_file.close()

I'm not 100% sure of the code above ... comes from 2 classes I've got for image manipulation ... but give it a try.

If is a InMemoryUploadedFile your code should work!


Post a Comment for "Django PIL : IOError Cannot Identify Image File"