Alex Onofre
Alex Onofre

Reputation: 365

How to compress images before uploading them to Amazon s3 using django storages and django rest framework?

I'm trying to compress the images before uploading them to the amazon s3 server, but I couldn't do it, I used 'PIL', to do it, but it didn't work

This is the code I used with the library '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)

Upvotes: 1

Views: 1031

Answers (1)

Alex Onofre
Alex Onofre

Reputation: 365

I solved it using the following code

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)

Upvotes: 2

Related Questions