What is the most straightforward method to resize an image file uploaded via a Django form as an ImageField
?
Asked
Active
Viewed 3.6k times
24

Joel G Mathew
- 7,561
- 15
- 54
- 86

Ivan Š
- 1,024
- 2
- 10
- 15
-
3[What have you tried?](http://whathaveyoutried.com) – arulmr Mar 20 '13 at 09:33
-
Use PIL for the job: http://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio – Krzysztof Szularz Mar 20 '13 at 09:34
-
you need to use an external library or an app to achieve that as django does not have any pre-defined methods for what you are looking to do. – Amyth Mar 20 '13 at 11:38
-
Is there any way to re-open this closed question so that I can share my modern solution? (Django 2.0 and Python3.6). – Nostalg.io Jun 11 '18 at 20:08
-
https://stackoverflow.com/a/57637103/4816270 – Pratik Saluja Aug 24 '19 at 10:28
2 Answers
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
-
2Thanks 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:
http://djangosaur.tumblr.com/post/422589280/django-resize-thumbnail-image-pil
http://davedash.com/2009/02/21/resizing-image-on-upload-in-django/
-
-
-
-
1Not a single link is a complete example for my use case, I had problems integrating the code in my previous attempts. – Ivan Š Mar 20 '13 at 12:23
-
7This answer would be better with code examples in the answer and not just links to other websites that may be down at the time you try to click the link. – teewuane Jul 13 '15 at 21:06