django - 保存前如何使用PIL调整新上传的图像的大小?

标签 django python-imaging-library django-models

我想在800px的高度和宽度中调整新图像的大小并保存。而且应用程序不得存储真实图像。有什么帮助吗?

这是我的代码,它保存原始图像,而不是调整大小的照片:

models.py:

class Photo(models.Model):        
    photo = models.ImageField(upload_to='photos/default/')


    def save(self):

        if not self.id and not self.photo:
            return            

        super(Photo, self).save()

        image = Image.open(self.photo)
        (width, height) = image.size

        "Max width and height 800"        
        if (800 / width < 800 / height):
            factor = 800 / height
        else:
            factor = 800 / width

        size = ( width / factor, height / factor)
        image.resize(size, Image.ANTIALIAS)
        image.save(self.photo.path)

最佳答案

image = image.resize(size, Image.ANTIALIAS)


调整大小是非破坏性的,它返回一个新图像。

关于django - 保存前如何使用PIL调整新上传的图像的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7970637/

相关文章:

python - Pypi:我可以声称自己是未维护包的新维护者吗?

python - 是否支持 Python 3.5 并使用 Postgresql?

python - 在python中对一串数据的文件类型进行指纹识别

python - 我将如何使用 django.forms 使用模型中的行预填充选择字段?

django - 如何在 django 模型中设置字段常量

django - 是否有任何 Django 包可以为谷歌云存储资源创建签名 url?

python - MySQL AB,HKEY_LOCAL_MACHINE 中的 MySQL Server 5.5 文件夹不存在

python-3.x - PIL.ImageEnhance 增强颜色、亮度和对比度功能的公式是什么?

python - Django 和枕头

django 外键在 HyperlinkedModelSerializer 中是什么类型的值