24

What is the most straightforward method to resize an image file uploaded via a Django form as an ImageField?

Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86
Ivan Š
  • 1,024
  • 2
  • 10
  • 15

2 Answers2

33

I was annoyed that I couldn't find a complete working example, only bits here and there. I managed to put the solution together myself. Here is the complete example, I put it in clean() method of the form (you can also override models save() method, in the completely same way - changing ImageField's file property).

import StringIO
from PIL import Image

image_field = self.cleaned_data.get('image_field')
image_file = StringIO.StringIO(image_field.read())
image = Image.open(image_file)
w, h = image.size

image = image.resize((w/2, h/2), Image.ANTIALIAS)

image_file = StringIO.StringIO()
image.save(image_file, 'JPEG', quality=90)

image_field.file = image_file
Ivan Š
  • 1,024
  • 2
  • 10
  • 15
  • 2
    Thanks for this example but I don't understand everything... What is "info" ? Otherwise, in python 3.x it's io.StringIO(...) – HydrUra Sep 27 '13 at 10:15
7

You could use PIL and resize the image in YourModel.save() method.

Examples:

resize image on save

http://djangosaur.tumblr.com/post/422589280/django-resize-thumbnail-image-pil

http://davedash.com/2009/02/21/resizing-image-on-upload-in-django/

Community
  • 1
  • 1
Efrin
  • 2,323
  • 3
  • 25
  • 45