Python Image Library, Close method

Posted by DNN on Stack Overflow See other posts from Stack Overflow or by DNN
Published on 2010-03-15T17:28:09Z Indexed on 2010/03/15 17:29 UTC
Read the original article Hit count: 879

Filed under:
|
|

Hello, I have been using pil for the first time today. And I wanted to resize an image assuming it was larger than 800x600 and also create a thumbnail. I could do either of these tasks separately but not together in one method (I am doing a custom save method in django admin). This returns a "cannot identify image file" error message.

The error is on the line "image = Image.open(self.photo)" after "#if image is size is greatet than 800 x 600 then resize image."

I thought this may be because the image is already open, but if i remove the line I still get issues. So I thought I could try closing after creating a thumbnail and then reopening.

But I couldn't find a close method....

This is my code:

    def save(self):

    #create thumbnail
    Thumb_Size = (75, 75)
    image = Image.open(self.photo)

    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')

    image.thumbnail(Thumb_Size, Image.ANTIALIAS)

    temp_handle = StringIO()
    image.save(temp_handle, 'jpeg')
    temp_handle.seek(0)

    suf = SimpleUploadedFile(os.path.split(self.photo.name)[-1],
        temp_handle.read(), content_type='image/jpg')
    self.thumbnail.save(suf.name+'.jpg', suf, save=False)

    #if image is size is greatet than 800 x 600 then resize image.
    image = Image.open(self.photo)
    if image.size[0] > 800:
        if image.size[1] > 600:
            Max_Size = (800, 600)

            if image.mode not in ('L', 'RGB'):
                image = image.convert('RGB')

            image.thumbnail(Max_Size, Image.ANTIALIAS)

            temp_handle = StringIO()
            image.save(temp_handle, 'jpeg')
            temp_handle.seek(0)

            suf = SimpleUploadedFile(os.path.split(self.photo.name)[-1],
                temp_handle.read(), content_type='image/jpg')
            self.photo.save(suf.name+'.jpg', suf, save=False)

    #enter info to database
    super(Photo, self).save()      

© Stack Overflow or respective owner

Related posts about pil

Related posts about python