BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage Articles 3 Easy Solutions to Optimize Images on the Fly

3 Easy Solutions to Optimize Images on the Fly

Key Takeaways

  • Images on web pages are typically the biggest contributor to page load time.
  • Optimizing images is complex, involving resizing, cropping, format conversion and fine tuning quality parameters.
  • Today there are cloud services that optimize images on-the-fly and can dramatically improve user experience for web pages with images.
  • The cloud services offer simple APIs to manipulate the images.
  • Readers can quickly evaluate one of the services and dramatically improve website performance with low effort.

When pages are slow to load, images are frequently the culprit. According to several studies, the megabyte size of web pages is steadily growing, and images are by far the largest component. It is clear that by optimizing images, most websites will achieve a dramatic performance boost.

In this article, we’ll show how image optimization can be achieved easily and automatically with a few lines of code, using three different cloud services: Kraken.io, Cloudinary, and Imgix. By implementing one of these services, you can immediately reduce image file size across your website and dramatically improve page load times and bandwidth usage.

What Does Image Optimization Entail?

Before we show how to automatically optimize your images, let’s establish the primary elements of image optimization: image sizing and resizing, image format, and image quality or compression. Here are common steps which can be taken to optimize images in line with each of these elements:

  1. Resize and crop images to the actual size they are supposed to occupy on the web page. Browser-side resizing is considered bad practice because it forces the user to download unnecessarily large images.
  2. Convert images to the most appropriate file format. This may differ for different types of images; in some cases PNG is the most optimal format, in other cases JPEG. If the user has a modern browser, it is possible to use new file formats supported by that browser. For example, the WebP format which is only supported in Chrome, or JPEG-XR which is supported in IE9 and above.
  3. Fine-tune compression on the target file format. For example, JPEG images have a quality setting. Specifying a quality percentage lower than 100% will compress the image, but at the same time result in degradation of visual quality. The art of optimization is to find the highest level of compression which does not result in visible quality loss (the image does lose quality with compression, but only slightly, so that a human wouldn’t notice it). The exact compression threshold will vary from image to image and from format to format.

Another optimization is stripping unnecessary metadata from the files. Most photos contain metadata stored by cameras and graphic applications, which is unnecessary for the end user and inflates image size. All the image optimization services we cover in the article strip this metadata along the way.

The steps above are time consuming, and require expertise to achieve a perfect result. For a website with only a few images, it might be possible to optimize the images by hand. However, on modern websites with as many as dozens or hundreds of images on one page, automation is needed.

Let’s see how we would manually optimize an image. We’ll then show you, step by step, how to achieve the same optimization automatically using each of the cloud image services.

Here is our reference image. It is a PNG file 2048 X 1365 pixels in size, weighing 3,975 KB.

Source: Marika Mariani on Flickr

To make this a more difficult case and stretch the abilities of the different tools, let’s say that this landscape-orientation image needs to fit into a tall portrait-oriented area on our webpage. Here is the sample web page, borrowed from the Wikipedia entry on Parrots:

(Click on the image to enlarge it)

In order to fit this image into the webpage and optimize it, we’ll need to perform the following steps:

  1. Resizing and cropping the image so that the parrot is visible in the available space, without losing the aspect ratio of the original image. This will dramatically reduce image size.
  2. Converting from PNG to a more efficient file format for the image, such as JPEG.
  3. Compressing the image to reduce file size but without degrading visible image quality.

Each of these three steps significantly reduces file size, without visibly hurting quality. Taken together, if we resize the image, convert to a leaner file format and fine-tune that format’s compression parameters, the resulting file size will be a fraction of the original.

Now let’s see how this transformation can be performed automatically by each of the three image management services, and what file size reduction they are able to achieve at each stage.

Keep in mind: this is not a benchmark. Optimized file size may differ for images with different content and composition. So this is not an absolute test of the efficacy of the different services, and that efficacy may vary for different types of images.

Optimizing Images with Kraken.io

Kraken.io is a cloud service specifically focused on image optimization. Its free plan provides 100 MB of image storage.

Kraken provides an API which allows you to programmatically upload an image, or provide a URL pointing to the image. Within the same API call, you can instruct the service to perform specific optimizations on the image, and download a new, optimized version.

Here is how to optimize our parrot image in Kraken:

  1. Sign up to Kraken, install the relevant SDK, authenticate yourself and pass the image to Kraken using a POST request.

    Using Kraken’s PHP SDK, this can be done as follows:
    $kraken = new Kraken("your-api-key", "your-api-secret");
    
    $params = array(
        "file" => "/path/to/image/parrot.jpg",
        "wait" => true
    );
    
    $data = $kraken->upload($params);
  2. The above code only uploaded the image. We need to resize the image to the required dimensions of 190 X 270 px, while cropping it so we retain focus on the parrot and do not lose aspect ratio; we can’t just scale the image to these dimensions, as it will become distorted.

    To resize and crop the image, we’ll modify the above code, adding a few parameters. "strategy" => "fit" specifies that the image should be resized to the required dimensions, retaining the original aspect ratio. "crop_mode" => "e" or "East" says the image should be cropped focusing on its Eastern side, where the parrot appears.
    $params = array(
    	   …
            "resize" => array(
            "width" => 190,
            "height" => 270,
            "strategy" => "fit",
            "crop_mode" => "e"
        )
    );
    The response to the API call contains a URL, from which you can download the optimized file. It looks like this:

    The file size is down to 105 KB, still with no optimization except for resizing.

    Note: By default the Kraken API strips all metadata from the image, so when we resized the file, it automatically removed metadata as well to reduce file size a bit more. The same is true for the other services we reviewed.
  3. Now let’s convert from PNG to JPEG:
    $params = array(
    	…
        "convert" => array(
           "format" => "jpeg",
           "background" => "#ff0000"
    	)
    )
    The modified API call returns a different download URL, with the image in JPEG format:

    The file size is now down to 88 KB.
  4. Finally, we’ll optimize JPEG quality. This is where an image optimization solution like Kraken shines. Kraken provides a simple parameter called lossy. By adding this to the image parameters in the API call, we instruct Kraken to reduce the JPEG to the lowest possible quality level, where the difference in quality will be imperceptible to the human eye.
    $params = array(
    	…
        "lossy" => true
    )
    The result appears very similar to the above, but has lower JPEG quality:

    This new file weighs only 29 KB, a 72% reduction compared to the resized PNG image. This improvement is purely due to image compression, because we had already previously resized the PNG image.

    This is the maximum Kraken was able to compress the image without hurting perceived visual quality. Compared to the original file size of 3,975KB, this is a total reduction of 1:137 in file size.
  5. A further optimization is to convert the image, instead of to JPEG, to the optimized WebP file format. The downside here is that WebP is only supported by the Chrome browser. To do this, we replace the convert parameter with the webp parameter, and leave the lossy parameter which optimizes the WebP image to the lowest possible size.
    $params = array(
    	…
        "webp" => true,
        "lossy" => true
    )
    The result looks like this (will only be visible on a Chrome browser).

    The final WebP file weighs only 11 KB, an 89% reduction compared to the resized PNG, and a total reduction of 1:361 compared to the original file size.

    Below is the full PHP code that generated this result with the Kraken API. The last line obtains the URL from which the optimized email can be downloaded.
    require_once("Kraken.php");
    
    $kraken = new Kraken("your-api-key", "your-api-secret");
    
    $params = array(
        "file" => "/path/to/image/parrot.jpg",
        "wait" => true
        "resize" => array(
            "width" => 190,
            "height" => 270,
            "strategy" => "fit",
            "crop_mode" => "e"
            "webp" => true,
            "lossy" => true
    );
    
    $data = $kraken->upload($params);
    
    $result = $data["kraked_url"];
    Note: Kraken emphasizes that the result URL should not be used as-is on a website, rather the application should download the image, store it locally and deliver it with a local URL.

Optimizing Images with Cloudinary

Cloudinary is a cloud image service that performs image optimization, and also provides a wide range of image manipulations, cloud storage and CDN delivery. Cloudinary’s free plan provides 2GB cloud storage, 75,000 images and 7,500 image transformations per month.

Cloudinary uses a different architecture to Kraken. In Cloudinary, you upload images to permanent cloud storage, and then the Cloudinary service delivers images directly to your website users.

A dynamic URL syntax specifies the image manipulations or optimizations that are required. When a parameter in the URL changes, the image is modified on the fly and delivered to the user in its modified form. The other service in our review, Imgix, uses a similar approach. 

Here is how to optimize our parrot image in Cloudinary:

  1. Sign up to Cloudinary and upload the image using the admin UI, or by installing the Cloudinary SDK and using the upload function. In the PHP SDK it looks like this:
    public static function upload($file, $options = array())
    Note: Unlike in Kraken, we do not pass image manipulation parameters in the options array, because image manipulation is done on-the-fly afterwards. Cloudinary provides additional upload options, including client side upload which enables users to upload their own users. For more details see Cloudinary’s PHP image upload documentation.
  2. Let’s resize and crop the image to 190 X 270 px, retaining the aspect ratio.
    cl_image_tag(
         "parrot.png", 
         array(
              "width"=>190, 
              "height"=>270, 
              "crop"=>"fill",
              "gravity"=>"auto")
         )
    )
    The "gravity" => "auto" parameter is a Cloudinary feature which automatically focuses on the most prominent object in the image, using object detection. This is a more scalable approach that doesn’t require adjusting parameters for each image.

    The code above generates an HTML image tag pointing to the dynamic image URL, for example:
    <img src=”http://res.cloudinary.com/agile-seo/image/upload/h_270,w_190,c_fill,g_auto/parrot_marika_mariani.png”>

    The new file weighs 103 KB.
  3. We’ll convert the file from PNG to JPEG. In Cloudinary this only requires changing the file extension:
    cl_image_tag(
         "parrot.jpg", 
         array(
               "width"=>190, 
               ...
         )
    )
    

    The file size is now 27 KB. This is much lower than we would expect for a full-quality JPEG image, suggesting Cloudinary is already performing some optimization on the image.
  4. Next, we’ll fully optimize JPEG quality by adding the Cloudinary "quality"=>"auto" parameter.
    cl_image_tag(
         "parrot.jpg", 
         array(
              …
              "quality"=>"auto"
              )
         )
    )
    

    File size is now 15 KB, a reduction of 85% compared to the resized PNG image.

    In total, Cloudinary achieves a reduction of 1:265 compared to the original file size.
  5. Let’s convert the image to a more optimized file format. Cloudinary provides the "format"=>"auto" parameter which sets a format for the image dynamically depending on the user’s browser (converting the image on-the-fly to that format). On a Chrome browser, this will automatically result in a WebP image. On new version of Explorer, it will deliver JPEG-XR.

    Note: The file extension still says ".jpg" but in reality the format is automatically decided based on image analytics and the user’s browser. If you view the URL above in Chrome, and download the image, you’ll see it is in WebP format.

    In WebP format and with quality optimization, the image weights 12 KB. Cloudinary’s WebP optimization provides 20% reduction in file size over the optimized JPEG.

    Another important note is that Cloudinary delivers images via a CDN. This does not affect file size, but is an additional optimization that allows users to retrieve images much more quickly.

Optimizing Images with Imgix

Imgix works similarly to Cloudinary: you upload an image, and then generate a dynamic URL in your code, to perform different optimizations on the image. Like Cloudinary, it is a full-featured image management solution offering a large number of image manipulations, cloud storage and CDN delivery.

Imgix offers a free trial which allows approximately 3,000 API-based image manipulations.

Here is how to optimize our parrot image in Imgix:

  1. Sign up to Imgix. Imgix does not support direct upload of images, so we will need to place the image in an existing web folder and connect to it from the Imgix dashboard. The image will then be accessible via your Imgix subdomain, e.g. agileseo.imgix.com/my_image.png
  2. Let’s crop and resize the image. Using the Imgix PHP SDK, the code to generate the dynamic image URL is as follows:
    use Imgix\UrlBuilder;
    
    $builder = new UrlBuilder("demos.imgix.net");
    $params = array(
               "w" => 190, 
               "h" => 270,
               "fit" => "crop",
               "crop" => "edges",
         );
    echo $builder->createURL("parrot_marika_mariani.png", $params);
    
    The w, h, fit and crop parameters resize the image while focusing on the parrot. Imgix has an "edge detection" feature (activated by "crop" => "edges") which crops while focusing on the part of the image that is of most interest.

    The resulting image size is 119 KB.
  3. We’ll now add the parameter "fm" => "jpeg" to convert the image to JPEG.

    The resulting file size is 24 KB.
  4. And we’ll add the parameter "auto" => "compress" to optimize JPEG compression.

    The final optimized JPEG weighs 13 KB, a reduction of 89% compared to the resized PNG image size.
  5. Like Cloudinary, Imgix provides a parameter that automatically selects the best image format based on the image and the user’s browser. The parameter is "auto" => "format".

    The file size in WebP is actually larger than the compressed JPEG, 24K. This is a bit of a mystery, but it seems to us that Imgix does not permit use of the "compress" and "format" options together (we tried with no effect), so that when "auto=format" is selected a WebP image is provided, but without optimal compression.

    Even without WebP compression, in JPEG format Imgix managed to reduce file size by 1:305.

    Like Cloudinary, Imgix delivers images via a CDN, which has an additional impact on how fast users retrieve images.

A Summary of Our Results: Image File Size Slashed by More Than 250X

As mentioned above, this article is not intended as a formal benchmark, but can give you some idea of the file size reductions that automatic image optimization can achieve.

The following table summarizes the optimizations we performed with the three tools. As shown above, the images generated by all the services appear visually perfect, despite the massive reduction in file size and the reduction in image quality.

Optimization Step Kraken Cloudinary Imgix
Original Image 3975KB 3975KB 3975KB
Crop and Resize
(still as PNG)
105KB 103KB 119KB
Convert to JPEG 88KB 23KB 24KB
Optimize JPEG Compression 29KB 15KB 13KB
Optimize by Conversion to WebP

15KB*
* Service does not support automatic WebP conversion

13KB

N/A*

* Service converted the image to WebP but it unexpectedly increased image size

Total file size reduction

1:265 with WebP support

1:137 without WebP

1:305 with WebP support

1:265 without WebP
1:305 without WebP

Interestingly, for this specific reference image, both Cloudinary and Imgix were so efficient with JPEG conversion that they reduced file size almost to the level of a WebP image. Your mileage may vary, depending on image content, composition and complexity.

The motivation for implementing automated image optimization is clear: Nearly effortless, on-the-fly reduction of image file sizes, which can have a dramatic impact on website performance. All three services we reviewed are easy and free to get started with, and we encourage you to try them out and get your website’s images in shape.

Know of additional tools or methods to optimize images automatically? Or have any thoughts on the services we reviewed? Share them with us in the comments!

About the Author

Gilad David Maayan is a technology writer who helps leading technology brands elucidate their products to new audiences. He is also CEO and founder of Agile SEO which brings together developers, IT leadership and relevant content via the search engines.

Rate this Article

Adoption
Style

BT