How to Optimize and Compress Image Files

image optimization and compression

Images are normally a large part of all the assets on a website and the visual content is growing. It is crucial to take image optimization serious in order to improve website performance. Google made performance a ranking factor as it impacts the user experience. And they do measure image performance – their PageSpeed Insights tool shows just how effective their algorithms are for measuring image speed. There are two good reasons to start taking image optimization into the web development process – page loading time and SERP ranking.

Replace Unnecessary Images

Eliminating images can be as simple as re-evaluating your design decisions. A simpler design can have more impact, and less visual clutter can help to get the message across without distraction. That said, an image or graphic effect might be integral to the design. Can you achieve the same effect without including the image file? Here are some alternatives to consider:

  1. CSS only backgrounds: You can often replace simple background images with gradients or CSS patterns.
  2. Use CSS effects: Drop shadows, glows, and transparency are all possible in CSS3. CSS3 even supports smooth key-frame animation, which goes a long way towards making flash redundant.
  3. Vector based Web fonts: There are many fonts to choose from, with Google providing decorative and conservative fonts for free. Web fonts have enabled designers to use more creative typefaces without having to render the text as an image. In fact, there are even icon web fonts, such as FontAwesome, which provide hundreds of high-quality icon vectors to use on your site.

Prefer Vector Images where Possible

Whenever you are dealing with simple geometrical shapes, two-dimensional illustrations, or images with flat areas of color, vector images are a good alternative to rasters. SVG vector graphics can much smaller than bitmaps, even before compression. They’re not just smaller, either. They look much better when scaled, as they are essentially curves, lines, and shapes, rather than pixels. So they don’t have a jagged edge, they remain sharp and crisp at any size.

Vector graphics are defined as points and numbers – they are essentially mathematical data. The SVG format is an XML dialect, which means it’s text based. It can be minified and compressed, just like CSS and JavaScript.

Choose the Right Raster Format

There are three different raster file formats that are useful on all browsers. PNG, GIF, and JPEG. Each one is great for a certain purpose. PNGs are good when it’s necessary to preserve a high level of detail. They work well for intricate patterns, or images with details that must be preserved, like a screen capture containing text. However, if the image is just text, it makes more sense to use HTML. It uses less bandwidth, and it’s better for the user, who can search the text, or copy-and-paste it. Before PNGs, GIF was the best choice for non-photographic images. The PNG format offers more features than GIF, and can be up to 25% smaller. GIFs are only a better choice when you need an animated image. JPEGs are ideal for photographs. They use a special lossy compression algorithm that discards details the human eye cannot see normally. It’s possible to fine-tune this algorithm to get the best results.

Serve the Right Resolution for the Right Device

One of the biggest sins web developers make is loading a large raster image and scaling it down in CSS. If the image is shrunk to half its original size that means that your user has downloaded an image that is twice the necessary width and height. That means that the file is four times larger than necessary (2 x 2).

Another factor to consider is the processor power that must be used to scale these images. Scaling can cause delays rendering a page. It can also cause visual artifacts (on some versions of Android there are noticeable glitches when a scaled image is scrolled or animated). When a mobile device downloads files intended for a desktop display, it will usually scale them down automatically. Automatic scaling carries all the same disadvantages of deliberate scaling images in CSS. By exporting multiple versions of the file for each resolution, you can serve the right version for the target device. Responsive image techniques make it possible to load different image files for different screen sizes. There are several responsive image techniques:

  1. The srcset attribute in the <img /> tag allows to defines possible resolutions that the browser can choose from. Here an example:
    <img src="/img/keycdn-600.jpg"
          alt="KeyCDN"
          srcset="/img/keycdn-300.jpg 300w,
                  /img/keycdn-600.jpg 600w,
                  /img/keycdn-1200.jpg 1200w" />

    Most modern web browsers support srcset, except IE and opera mini.

  2. Use client detection on the server to select the right file.
  3. Use the “clown car” responsive image technique. It is an interesting approach that gets around some of the problems associated with client detection, which is not infallible.
  4. Lazy-loading with JavaScript. Lazy loading defers the loading of a page’s images until after the page has rendered. Often they are not loaded until the user has scrolled the screen to the point where the image should be. JavaScript can detect the dimensions of the device, and can load the correct image resolution. LazySizes is a lightweight JavaScript library that makes it easy to implement lazy loading.

Get Rid of the Metadata

Often, images files are cluttered with information that the web browser doesn’t need. Metadata in the file can include all kinds of junk, like geo data and camera information. There are simple programs to remove this redundant data from image files, and smart compression tools to make files even smaller.

Compress Image Files

Image compression can make your images much lighter without sacrificing quality. Note that it’s a good idea to optimize images after scaling them, to prevent artifacts. Often, an SVG file may have metadata from the editor (such as layers, comments and other odds and ends). An SVG optimizer like svgo can strip this useless data. SVG is an XML dialect, so it may contain unnecessary whitespace. Minification will eliminate whitespace and comments. You can compress the minified file by enabling GZIP compression in your CDN settings or configure it on your origin server to make it even smaller, without losing any data. Raster graphics contain data for each pixel, arranged in a grid. Each pixel has four separate channels: red, green, blue and alpha (transparency). By default, each channel uses 8 bits (one byte) for up to 256 degrees of red, green, blue or alpha. That’s four bytes for each pixel. It is possible to tweak this, to use fewer bits per channel. Of course, that means that there will be less subtle variation between shades in the image. Often, it’s possible reduce to 7 or 5 bits without degrading the image noticeably. The JPEG algorithm has several settings you can play with to get the best result. Most image editors give you a “quality” slider that you can drag, but there are other more advanced options that you can experiment with. Besides trying out different options in the compression dialog, there are advanced image editing tactics that will help to produce the smallest possible file. PNG images can be indexed, which means that each pixel will have a color from a limited palette. If your image does not have a lot of color variation or has only a few colors, then indexing is a great way to shrink your file. Smashing Magazine has published an advanced guide to optimizing PNGs.

Automating Compression

optimus.io is an image optimiztaion service that provides a simple API you can send your images and receive the compressed image. optimus.io has also a WordPress plugin called Optimus that optimizes the image during the upload process. JPEG, PNG and WebP are the supported image formats.

Image optim is a suite of command line tools to optimize and compress almost any type of image. It uses several different programs to do so, but it makes the whole process simple because it’s a single program instead of 11. You can use it to compress an entire directory full of images with a single command.

Excellent possibilities to automate image compression offer the task automation systems Gulp and Grunt. The plugins gulp-imagemin and grunt-contrib-imagemin are commonly used to compress images.

TL;DR

There are a lot of tools and options that you can use to optimize your images. Follow the steps outlined above, and your images will be much smaller. Of course, it’s possible to tweak and fuss over optimization long after you’ve achieved the desired goal. It’s useful to have a yardstick to measure your site against, to see when you need to optimize more, and when you are done. Google’s PageSpeed Insights can score your site and point out any files that need improvement.

Happy optimizing!

Related Articles

How to Optimize and Compress Image Files was last modified: April 25th, 2016 by Gary Witt
Share This