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

前端之家收集整理的这篇文章主要介绍了django – 如何在保存之前使用PIL调整新上传的图像大小?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想调整高度和宽度为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)

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

原文链接:https://www.f2er.com/python/185666.html

猜你在找的Python相关文章