如何使用ImageField模型调整通过Django上传的图像文件的大小? [英] How can I resize an image file uploaded with Django using an ImageField Model?
本文介绍了如何使用ImageField模型调整通过Django上传的图像文件的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将通过Django表单上传的图像文件调整为ImageField
的最直接方法是什么?
What is the most straightforward method to resize an image file uploaded via a Django form as an ImageField
?
推荐答案
我很生气,因为我找不到一个完整的工作示例,只能在这里和那里找到一些地方.我设法自己解决了问题.这是完整的示例,我将其放在表单的clean()方法中(您也可以以完全相同的方式覆盖模型save()方法-更改ImageField的file属性).
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
这篇关于如何使用ImageField模型调整通过Django上传的图像文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文