如何使用 ImageField 模型调整使用 Django 上传的图像文件的大小? [英] How can I resize an image file uploaded with Django using an ImageField Model?

查看:22
本文介绍了如何使用 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 的文件属性).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆