# Optimizers

Even though GD and Imagick (the PHP extensions available for transforming images) are good at transforming and manipulating images, they are in no way delivering images optimized for file size. Images being the single biggest factor in most websites' total load, it's essential to try to optimize them as much as possible. This is what optimizers in Imager is for.

Optimizers are command line tools or services that receive a transformed file, optimize it, and replaces the original file with the optimized one. Optimizers can be run either asynchronously as a queue job (default behaviour), or runtime when the transform is created.

Imager comes with nine built-in optimizers; jpegoptim (opens new window), jpegtran (opens new window), mozjpeg (opens new window), optipng (opens new window), pngquant (opens new window), gifsicle (opens new window), tinypng (opens new window), kraken (opens new window) and imageoptim (opens new window). The first six are command line tools, while the last three are services that you need to sign up to use.

TIP

You can also make your own optimizer for whatever tool or service you want, check out the docs about extending Imager with new optimizers.

After setting up your optimizers, you don't have to do anything more. Your template code stays the same, and as long as your configuration is correct, and your queue runs, your transformed images will be optimized.

# Configuration

There are three config settings involved in setting up optimizers; optimizers, optimizeConfig and optimizeType.

In optimizerConfig you configure the different optimizers. Some tools may already be available in your environment, others might have to be installed. Imager comes with some default configuration for the built-in optimizers (as seen here), but these are mostly just to provide an example. You need to make sure that all file paths and credentials are correct, and optimize the command line params to your liking.

Also note that each optimizer must be set up to process a given set of extensions. Only files with these extensions will be run through the optimizer. You can run several optimizers on the same extensions, but it's probably a good idea to only have one optimizer (the best) per file type.

With your optimizers configured, you can now choose which optimizers to enable through the optimizers config setting. This enables you to have different optimizers enabled in different environments, and also override on a per transform basis.

Lastly, the optimizeType config setting let's you decide if you want the optimizers to run as a queue 'job' (default) or 'runtime'. Since optimizing images is a very resource intensive and time consuming process, you probably want the former. But, when debugging it's also very useful to set it to 'runtime' so that you can catch any errors in your templates.

Let's have a look at how to bring this together.

# A practical example: "Free for life"

In this example, we'll use some open source command line tools that installs directly on the server. It's a cheap solution that provides a decent improvement. We'll go with jpegtran (opens new window) for jpegs, optipng (opens new window) for pngs and gifsicle (opens new window) for gifs. These are classic tools that have binaries and packages on most popular platforms, and are often already installed in your hosting environment. I won't go into how to install them, check out the tools' websites, they explain it better than me.

Now, let's configure them by adding this to our config file:

'optimizerConfig' => [
    'jpegtran' => [
        'extensions' => ['jpg'],
        'path' => '/usr/bin/jpegtran',
        'optionString' => '-optimize -copy none -progressive',
    ],
    'optipng' => [
        'extensions' => ['png'],
        'path' => '/usr/bin/optipng',
        'optionString' => '-o5 -strip all',
    ],
    'gifsicle' => [
        'extensions' => ['gif'],
        'path' => '/usr/bin/gifsicle',
        'optionString' => '--optimize=3 --colors 128',
    ],
],

If you compare this to the default settings, you can see that I've modified the options for the tools somewhat. I'm telling jpegtran to make all jpegs progressive, I've increased the optimization of pngs to 5 and asked optipng to strip out all meta data, and I'm reducing the color depth of gifs to 128. Again, you have to decide what options are the best for your project.

Now, the next thing we need to do is enable the optimizers by adding the following to the config file:

'optimizers' => ['jpegtran', 'optipng', 'gifsicle'],

That's all that's needed to optimize your transforms!

TIP

The tools I've chosen are some of the easiest to install. If you're not afraid of getting your hands dirty, you should look into mozjpeg (opens new window) and pngquant (opens new window). I've found these to generally deliver better compression, but they can be harder to install on your server.

As I hinted at earlier, you can override the optimizers on a per transform basis when needed. Let's say we have a section with some very special gifs that we don't want to be reduce to 128 colors (as per the gifsicle config), we can do it like this:

{% set transformedGif = craft.imagerx.transformImage(image, 
    [{ width: 800 }, { width: 1000 }, { width: 1200 }]),
    { ratio: 16/9, format: 'gif' },
    { optimizers: [] } 
%}

# A practical example: "Money money money"

This example is for the millionaire who doesn't care about money... No, not really. But if you're willing to spend a few dollars to offload the optimization to an external servie, kraken.io (opens new window) is a good option.

Contrary to the command line tools in the previous example, you can use this optimizer on whichever server and environment you're running. Imager will upload files to Kraken which will optimize them and send them back, and Imager will replace the original file with the optimized one.

The first step is to sign up for an account (opens new window) at kraken.io. After signing up, go to your dashboard and create a new set of API keys under "API Dashboard". We can now set up your optimizer config and enabled optimizers like this:

'optimizers' => ['kraken'],
'optimizerConfig' => [
    'kraken' => [
        'extensions' => ['png', 'jpg', 'gif'],
        'apiKey' => 'MY_API_KEY',
        'apiSecret' => 'MY_API_SECRET',
        'additionalParams' => [
            'lossy' => true,
        ]
    ],
],

As you can see, one of the big benefits of kraken.io is that it can transform both pngs, jpegs and gifs, so we only need this one optimizer.

TIP

Also, if you're not afraid of spending some extra dollars, consider offloading all your image transforms to Imgix (opens new window) by using the Imgix transformer.

# Final words

Even though we all want the smallest possible file sizes when dealing with transformed images, it's also a fact that image optimization is a brutally resource intensive operation (there's a reason for your laptop having a dedicated GPU (or four) in addition to your CPU). Performance can be an issue when going all in on optimization, so make sure that you weigh the pros and cons, and have realistic expectations as to what your server can handle. 🔥