How can I resize an image file uploaded with Django using an ImageField Model? [closed] How can I resize an image file uploaded with Django using an ImageField Model? [closed] django django

How can I resize an image file uploaded with Django using an ImageField Model? [closed]


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 StringIOfrom PIL import Imageimage_field = self.cleaned_data.get('image_field')image_file = StringIO.StringIO(image_field.read())image = Image.open(image_file)w, h = image.sizeimage = image.resize((w/2, h/2), Image.ANTIALIAS)image_file = StringIO.StringIO()image.save(image_file, 'JPEG', quality=90)image_field.file = image_file