0

how would you compress the image when the user uploads

from PIL import Image

class photo(models.Model):

    title = models.CharField(max_length=100)
    uploader = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)

    image_url = models.ImageField(upload_to='images', null=True)
Naterz
  • 387
  • 4
  • 14
  • Does this answer your question? [Losslessly compressing images on django](https://stackoverflow.com/questions/33077804/losslessly-compressing-images-on-django) – Harsh Nagarkar Jan 19 '20 at 00:16

1 Answers1

0

Do in save method

from PIL import Image

class photo(models.Model):

    title = models.CharField(max_length=100)
    uploader = models.ForeignKey(
    settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)

    image_url = models.ImageField(upload_to='images/', null=True)

    def save(self, *args, **kwargs):
        instance = super(photo, self).save(*args, **kwargs)
        img = Image.open(instance.image_url.path)
        img.save(instance.image_url.path,quality=20,optimize=True)
        return instance

The 'optimize' flag will reduce its size as much as possible.

Saroj Rai
  • 1,419
  • 14
  • 13