27

I'm doing optimization and Google recommends Lossless compression to images, looking for a way to implement this in Django.

Here's the images they specified, I think for it to be done effectively it needs to implemented systemwide possibly using a middleware class wondering if anyone has done this before. Here's the link to google analytics for pagespeed https://developers.google.com/speed/pagespeed/insights/?url=www.kenyabuzz.com

Optimize images Properly formatting and compressing images can save many bytes of data. Optimize the following images to reduce their size by 627.3KiB (74% reduction).

Losslessly compressing http://www.kenyabuzz.com/media/uploads/clients/kenya_buzz_2.jpg could save 594.3KiB (92% reduction).
Losslessly compressing http://www.kenyabuzz.com/media/uploads/clients/new_tribe_2.jpg could save 25KiB (44% reduction).
Losslessly compressing http://www.kenyabuzz.com/…a/uploads/clients/EthiopianAirlines2.jpg could save 3KiB (22% reduction).
Losslessly compressing http://www.kenyabuzz.com/static/kb/images/Nightlife.Homepage.jpg could save 1.3KiB (2% reduction).
Losslessly compressing http://www.kenyabuzz.com/static/kb/img/social/blog.png could save 1.1KiB (43% reduction).
Losslessly compressing http://www.kenyabuzz.com/static/kb/img/social/twitter.png could save 969B (52% reduction).
Losslessly compressing http://www.kenyabuzz.com/…der-Board---Email-Signature--Neutral.jpg could save 920B (2% reduction).
Losslessly compressing http://www.kenyabuzz.com/static/kb/img/social/youtube.png could save 757B (31% reduction).
  • Following the link https://developers.google.com/speed/docs/insights/OptimizeImages from the very page you reference provides a great deal of information. Have you read that yet? – mhawke Oct 12 '15 at 09:52
  • Yes I did but they don't provide information on how to implement the same with python or Django. I googled "Losslesly compressing images django" and didn't get any information on this. –  Oct 12 '15 at 09:59
  • Why do it in Django - there is a link from the Google optimize page that allows Google to do it for you. Grab those images, upload to server, collectstatic, and done. – professorDante Oct 12 '15 at 16:04
  • This project enable several of these options directly on the model. https://github.com/un1t/django-resized – MGP Nov 30 '15 at 02:10

3 Answers3

57

Losslessly compressing http://www.kenyabuzz.com/media/uploads/clients/kenya_buzz_2.jpg could save 594.3KiB (92% reduction).

First of all, the information in the logs is not very accurate.

92% lossless reduction is only possible when the original image is uncompressed and has very small number of colours (ideally less than 256).

Lossless compression involves reducing the "bit-depth" of an image, i.e. converting 24-bit images down to 8-bit if there are less than 256 colours, that means you're saving 16 bits per pixel. But that doesn't seem possible for the images you've linked because they have well over 256 colours.

Second, you can use lossy compression formats "without losing quality" – the differences are so subtle, human eye doesn't even notice.

Read this answer and this answer for more info. Really, do read them, both are excellent answers related to this issue.


So, I downloaded an image from the website you're optimizing from this link: http://www.kenyabuzz.com/media/uploads/clients/kenya_buzz_2.jpg

I opened my Python console and wrote this:

>>> from PIL import Image

>>> # Open the image
>>> im = Image.open("kenya_buzz_2.jpg")
>>> # Now save it
>>> im.save("kenya_buzz_compressed.jpg", format="JPEG", quality=70)

This created a new image on my disk. Below are both the images.

Original (655.3kB)

original image


Compressed (22.4kB ~96% reduction @ quality=70)

compressed image using Python


You can play around with the quality option. Like, value of 80 will give you a better quality image but with a little larger size.


Compressing images in Django

Since this is a pretty popular question, I've decided to add a sample code to compress images in Django.

This code works for Django >= 1.7.

from io import BytesIO
from PIL import Image
from django.core.files import File


def compress(image):
    im = Image.open(image)
    # create a BytesIO object
    im_io = BytesIO() 
    # save image to BytesIO object
    im.save(im_io, 'JPEG', quality=70) 
    # create a django-friendly Files object
    new_image = File(im_io, name=image.name)
    return new_image

And this is how you can use the above compress function in your Django model (or anywhere):

# models.py

class MyModel(...):
    image = models.ImageField(...)

    def save(self, *args, **kwargs):
        # call the compress function
        new_image = compress(self.image)
        # set self.image to new_image
        self.image = new_image
        # save
        super().save(*args, **kwargs)

That is basically it. This is fairly basic code. You can improve the code by compressing the image only when the image changes, not every time the model is saved.

xyres
  • 20,487
  • 3
  • 56
  • 85
  • 2
    Exactly, I'd use this at the upload part, or something like trimage for plain static images. – MGP Nov 30 '15 at 02:01
  • 1
    It doesn't work for me. I tried to reduce an image with 1MB but I got a new image with 1.9MB :| – Cristhian Boujon Jul 14 '17 at 20:01
  • @Overflow012 Are you setting `quality` value more than `95`? That has been known to increase file sizes. – xyres Jul 15 '17 at 15:48
  • @xyres, no, I'm using `quality=70` – Cristhian Boujon Jul 17 '17 at 01:21
  • @xyres but i don't want to save the new image in my disk, I just want to display compressed image in browser. – rahul mehra Mar 01 '18 at 09:33
  • @rahulmehra In that case, you can [write the image directly to response](https://stackoverflow.com/questions/3003146/best-way-to-write-an-image-to-a-django-httpresponse) and serve it. – xyres Mar 01 '18 at 10:07
  • this works to compress images locally, but unfortunately images won't be compressed this way when you serve files with the nginx server. – Conor Sep 12 '22 at 13:31
4

You should try Django Easy Thumbnails app, it has some options to add a postprocessing to optimize uploaded images : PostProcessor documentation

I use it in production on several projects. It works well, image size is definitely smaller and page loading much more faster.

2

I have no experience with it, however, picopt looks comprehensive. It relies extensively on external tools to perform the optimisation, so it might be difficult to set up in constrained or hosted server environments.

Other than that, try googling "python image optimization". There are a few other links that suggest that a PIL based solution might be possible, for example:

  1. How to reduce the image file size using PIL
  2. Image Optimization (Google App Engine with Python)
Community
  • 1
  • 1
mhawke
  • 84,695
  • 9
  • 117
  • 138