如何在django python中压缩上传的图像

时间:2018-04-04 08:53:25

标签: django python-3.x web django-templates

已经在python上学习了很多关于如何压缩图像的教程,使用PILLOW但它不起作用。如果我能在django views.py

中获得有关如何使用PILLOW进行图像压缩的完整文档,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

我之前在枕头中使用了缩略图()来压缩模型中的图像。py缩略图()在调整图像大小时不会改变图像的纵横比。

import sys

from django.db import models
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile

def compressImage(uploaded_image):
    image_temp = Image.open(uploaded_image)
    outputIoStream = BytesIO()
    image_temp.thumbnail( (1600,1600) )
    image_temp.save(outputIoStream , format='JPEG', quality=100)
    outputIoStream.seek(0)
    uploaded_image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploaded_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
    return uploaded_image

class ABC(models.Model):
    name = models.CharField(max_length=200)
    image = models.ImageField(upload_to=/upload/path/here/, null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.id:
            self.image = compressImage(self.image)
        super(ABC, self).save(*args, **kwargs)