Optimizing Images using a Postprocessor

The PIL and the Pillow libraries do a great job when is comes to crop, rotate or resize images. However, they both operate poorly when it comes to optimizing the payload of the generated files.

For this feature, two portable command line programs can fill the gap: jpegoptim and optipng. They both are open source, run on a huge range of platforms, and can reduce the file size of an image by often more than 50% without loss of quality.

Optimizing such images is a big benefit in terms of loading time and is therefore strongly recommended by tools such as Google’s PageSpeed. Moreover, if every website operator cares about, it reduces the overall Internet traffic and thus greenhouse gases by some googolth percent.

Support for these postprocessors (or other similar ones) is available as an optional feature in easy-thumbnails.

Installation and configuration

Install one or both of the above programs on your operating system.

In your Django project’s settings module, add the optimizing postprocessor to your configuration settings:

INSTALLED_APP = (
    ...
    'easy_thumbnails',
    'easy_thumbnails.optimize',
    ...
)

There is one configuration settings dictionary:

OptimizeSettings.THUMBNAIL_OPTIMIZE_COMMAND = {'gif': None, 'jpeg': None, 'png': None}

Postprocess thumbnails of type PNG, GIF or JPEG after transformation but before storage.

Apply an external post processing program to images after they have been manipulated by PIL or Pillow. This is strongly recommended by tools such as Google’s PageSpeed on order to reduce the payload of the thumbnailed image files.

Example:

THUMBNAIL_OPTIMIZE_COMMAND = {
    'png': '/usr/bin/optipng {filename}',
    'gif': '/usr/bin/optipng {filename}',
    'jpeg': '/usr/bin/jpegoptim {filename}'
}

Note that optipng can also optimize images of type GIF.