Django在上传期间调整图像大小 [英] Django resize image during upload

查看:864
本文介绍了Django在上传期间调整图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,是否可以在上传的图像保存到磁盘之前更改(调整大小)?我不喜欢这样做,而不使用任何额外的应用程序。

In Django, is it possible to change (resize) the uploaded image before it gets saved to the disk? I'd prefer to do this without using any extra apps.

推荐答案

我很烦,我找不到一个完整的工作例如,这里和那里只有位。我设法自己把解决方案结合在一起。这里是完整的例子,我把它放在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

这篇关于Django在上传期间调整图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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