nknj
nknj

Reputation: 2486

Resizing uploaded files in django using PIL

I am using PIL to resize an uploaded file using this method:

def resize_uploaded_image(buf):
  imagefile = StringIO.StringIO(buf.read())
  imageImage = Image.open(imagefile)

  (width, height) = imageImage.size
  (width, height) = scale_dimensions(width, height, longest_side=240)

  resizedImage = imageImage.resize((width, height))
return resizedImage

I then use this method to get the resizedImage in my main view method:

image = request.FILES['avatar']
resizedImage = resize_uploaded_image(image)
content = django.core.files.File(resizedImage)
acc = Account.objects.get(account=request.user)
acc.avatar.save(image.name, content)

However, this gives me the 'read' error.

Trace:

Exception Type: AttributeError at /myapp/editAvatar Exception Value: read

Any idea how to fix this? I have been at it for hours! Thanks!

Nikunj

Upvotes: 3

Views: 3662

Answers (2)

Cameron
Cameron

Reputation: 98776

Here's how you can take a file-like object, manipulate it as an image in PIL, then turn it back into a file-like object:

def resize_uploaded_image(buf):
    image = Image.open(buf)

    (width, height) = image.size
    (width, height) = scale_dimensions(width, height, longest_side=240)

    resizedImage = image.resize((width, height))

    # Turn back into file-like object
    resizedImageFile = StringIO.StringIO()
    resizedImage.save(resizedImageFile , 'PNG', optimize = True)
    resizedImageFile.seek(0)    # So that the next read starts at the beginning

    return resizedImageFile

Note that there's already a handy thumbnail() method for PIL images. This is a variant of the thumbnail code I use in my own project:

def resize_uploaded_image(buf):
    from cStringIO import StringIO
    import Image

    image = Image.open(buf)

    maxSize = (240, 240)
    resizedImage = image.thumbnail(maxSize, Image.ANTIALIAS)

    # Turn back into file-like object
    resizedImageFile = StringIO()
    resizedImage.save(resizedImageFile , 'PNG', optimize = True)
    resizedImageFile.seek(0)    # So that the next read starts at the beginning

    return resizedImageFile

Upvotes: 4

Zubair Afzal
Zubair Afzal

Reputation: 2086

It would be better for you to save the uploaded image and then display and resize it in template as you wish. This way you will be able to resize images at runtime. sorl-thumbnail is djano app which you can use for template image resizing, it is easy to use and you can use it in a view too. Here are examples for this app.

Upvotes: 1

Related Questions