如何在保存前使用 PIL 调整新上传的图像的大小? [英] How to resize the new uploaded images using PIL before saving?

查看:29
本文介绍了如何在保存前使用 PIL 调整新上传的图像的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以 800 像素的高度和宽度调整新图像的大小并保存它们.并且该应用程序不得存储真实图像.有什么帮助吗?

I want to resize the new images in a height and width of 800px and save them. And the app mustn't store the real image. Any help?

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

This is my code, it saves the original image and don't the resized photo:

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)

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

resize is non-destructive, it returns a new image.

这篇关于如何在保存前使用 PIL 调整新上传的图像的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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