在使用django存储和django rest框架将图像上传到Amazon s3之前如何压缩图像?

时间:2019-07-24 18:19:26

标签: django amazon-s3 django-rest-framework django-storage

我正在尝试压缩图像,然后再将其上传到amazon s3服务器,但是我做不到,我使用了'PIL'来做,但是没有用

这是我与库“ PIL”一起使用的代码:

from io import BytesIO
from PIL import Image
from django.core.files import File

def compress(image):
    im = Image.open(image)
    im_io = BytesIO() 
    im.save(im_io,'PNG', quality=70) 
    new_image = File(im_io, name=image.name)
    return new_image

class MyModel(models.Model):
    file = models.FileField(blank=True, null=True, validators=[validateFileSize])

    def save(self, *args, **kwargs):
        new_image = compress(self.file)
        self.file = new_image
        super().save(*args, **kwargs)

1 个答案:

答案 0 :(得分:1)

我使用以下代码解决了该问题

def compress(image):
        im = Image.open(image)
        # create a BytesIO object
        im_io = BytesIO() 
        # save image to BytesIO object
        #im = im.resize([500,500])
        im = im.convert("RGB")
        im = im.save(im_io,'JPEG', quality=70) 
        # create a django-friendly Files object
        new_image = File(im_io, name=image.name)
        return new_image


    class Media(models.Model):
        file = models.FileField(blank=True, null=True, validators=[validateFileSize])

        def __str__(self):
            return str(self.id)

        def save(self, *args, **kwargs):
            if self.file:
                if self.file.size > (300 * 1024):
                    # call the compress function
                    new_image = compress(self.file)
                    # set self.image to new_image
                    self.file = new_image
                    # save
            super().save(*args, **kwargs)