【问题标题】:How to compress images before uploading them to Amazon s3 using django storages and django rest framework?如何在使用 django storages 和 django rest framework 将图像上传到 Amazon s3 之前压缩图像?
【发布时间】:2019-12-02 23:15:12
【问题描述】:

我正在尝试在将图像上传到亚马逊 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)

【问题讨论】:

  • 你为什么不上传它并用s3事件触发lambda然后压缩它?哪个部分没有工作?你能提供上传到s3的代码的sn-p吗?您有任何错误消息吗?
  • @giaco 谢谢回答,我已经解决了
  • @AlexOnofre 你最后是怎么解决的?
  • Alex,你是怎么解决的?我也有同样的问题
  • @NicolasRizzo 我已经发布了我的解决方案

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


【解决方案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)

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 2020-10-11
    • 2015-07-18
    • 2020-09-23
    • 2014-07-01
    • 1970-01-01
    • 2016-03-23
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多