how to compress the image before uploading to s3 in django?

半城伤御伤魂 提交于 2019-12-06 21:54:29

So we need to define a save method in models in order to compress the image before save. Following code help me what I want to achieve for my problem.

class Report_item(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
    
    image = models.ImageField(default="add Item image",
                              upload_to=get_uplaod_file_name)

    def save(self):
        # Opening the uploaded image
        im = Image.open(self.image)

        output = BytesIO()

        # Resize/modify the image
        im = im.resize((100, 100))

        # after modifications, save it to the output
        im.save(output, format='JPEG', quality=90)
        output.seek(0)

        # change the imagefield value to be the newley modifed image value
        self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg',
                                        sys.getsizeof(output), None)

        super(Report_item, self).save()

WIth the help of this 5 Mb image compress to 4 kb approx.

Suppose you want to upload an image after resizing it. You can use below code, just pass the image object and you will get resized image in return.

def GetThumbnail(f):
    try:
        name = str(f).split('.')[0]
        image = Image.open(f)
        image.thumbnail((400, 400), Image.ANTIALIAS)
        thumbnail = BytesIO()
        # Default quality is quality=75
        image.save(thumbnail, format='JPEG', quality=50)
        thumbnail.seek(0)
        newImage = InMemoryUploadedFile(thumbnail,
                                   None,
                                   name + ".jpg",
                                   'image/jpeg',
                                   thumbnail.tell(),
                                   None)
        return newImage
    except Exception as e:
        return e
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!