Vadim Tikanov
Vadim Tikanov

Reputation: 671

PIL Image resize compresses the image when is not expected to

I have the following Django model with overriden save method:

class Photo(models.Model):
    image = models.ImageField(upload_to=get_file_path, blank=False, null=False)

    def save(self, *args, **kwargs):
        """
        Override save method to resize uploaded photo images to max_size.
        """
        if not self.id and not self.image:
            return

        super(Photo, self).save(*args, **kwargs)

        resized_image = Image.open(self.image)
        resized_image = resized_image.resize(settings.PHOTO_CONFIG['max_size'], Image.ANTIALIAS)
        resized_image.save(self.image.path)

And the following config in settings.py:

PHOTO_CONFIG = {
    'max_size': (900, 900),
}

Now, when I upload JPG of exactly 900x900 size (500 kb), the uploaded one is compressed to about 100kb. Both are 900x900 and 72 dpi resolution.

How and why does this happen?

Upvotes: 0

Views: 65

Answers (1)

Djizeus
Djizeus

Reputation: 4175

There could be several reasons for that, but in a nutshell it is probably because the default save parameters are not the ones used to create the original image.

It could notably be:

  • The original image was created with a higher quality. The default quality of Pillow is 75 (it can go from 1 to 95 (best)). A lower quality can sometimes reduce the size.
  • The original image had EXIF data (from a camera for example) or an ICC profile. By default, Pillow does not save any EXIF data or ICC profile.

See the complete list of options of the save method for JPEG file, and their default value, and you should find out which one is different in your case.

Upvotes: 1

Related Questions