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

对着背影说爱祢 提交于 2019-12-17 15:49:15

问题


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


回答1:


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



回答2:


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/



来源:https://stackoverflow.com/questions/15519716/how-can-i-resize-an-image-file-uploaded-with-django-using-an-imagefield-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!