Digital images and optimizing for the web, a whirlwind tour

Jorge Rodriguez
Backstage
Published in
9 min readJun 27, 2018

--

TuneIn SVG markup.

Decreasing the load time of your website is a journey, and part of that journey is optimizing assets like scripts, stylesheets, and images. Images often account for the bulk of network traffic when loading a web page, and so decreasing the file size of those images is critical.

In this article I’ll talk about vector graphics and raster images, including when it is appropriate to use each format and how to use them effectively. I’ll also cover file size optimization for both types of images, including example step by step processes.

It’s worth noting that much of the information included here is derived from Google’s image optimization guidelines, found here. It’s a great resource if you’d like to level up after reading this article.

Vector Graphics

When, why, and how should I use scalable vector graphics?

If possible, use a vector graphic (SVG). While raster image formats like JPEG and GIF have been around longer and are still better choices for photographic images, there are considerable benefits to using SVGs when possible. So much of image optimization is based on trying to minimize the file size of an asset while maintaining its visual integrity. This challenge is further complicated by the wide variety of devices now capable of browsing the web. SVG allows us to use a single XML-like text file that the browser can then render sharply at any size, for any screen resolution.

We use SVG almost exclusively for icons and logos on tunein.com. Of course, it’s worth noting that using SVG is not appropriate for every type of image. Photographic images will still require the use of raster image formats like JPEG, which I’ll discuss later in this article.

Where do SVGs come from?

Although you could write SVG markup by hand, it is more practical to use software to generate it. Here at TuneIn, our designers typically use either Sketch or Adobe Illustrator to create icons for tunein.com. Both of these applications ship with features that allow for the export of an image in SVG format.

After exporting vector graphics in Sketch for some time, we noticed that it produces SVG code that is unnecessarily verbose and complex; Sketch generates markup that includes masks where simple paths are sufficient. Therefore, we now request that any new icons created by our design team be exported using Adobe Illustrator. Illustrator uses simple paths and produces much smaller files. We can then use other tools to further reduce the file size.

If you’re not interested in how to export a custom asset from Adobe Illustrator, skip ahead to the next section.

The process for exporting an SVG in Adobe Illustrator (version 22.0.1) is as follows:

  1. Select the icon or image you would like to export.
  2. In the Illustrator application menu (top bar), select File > Export Selection…
  3. Choose SVG as the format

Before exporting, click the gear icon to check the settings for SVG export.

These are the settings we currently recommend, which can be adjusted according to your needs.

How can I optimize my SVG?

Google recommends a tool called SVGO for optimizing SVG markup. SVGO ships with a command line tool, but there are also a variety of wrapper applications that make it easier to use. A list of wrapper applications can be viewed on the SVGO Github page (linked above), including an easy-to-use web application called SVGOMG.

The goal when optimizing SVG markup should be to remove as much information as possible while maintaining the integrity of the image. SVGOMG has a set of defaults that will cover most bases. For extra credit, look over the output and remove any other extraneous attributes and structure. Some examples are `data-` attributes, title tags, and groupings (<g> tags) that may be extraneous.

Now you’re ready to add your SVG asset to your website.

There are different ways to get your SVG onto the page. At TuneIn, we are experimenting with primarily using SVGs as background images in our stylesheets, as opposed to inlining them in our HTML. This way we minimize the size of our initial HTML response and load our SVG assets asynchronously from the CDN. Using SVGs in this way also allows us to leverage CDN edge and browser caching. Your server should also be configured to compress SVG assets if you want to serve them in this way.

The style rule for an element that has an SVG asset as it’s background image might look something like this:

.checkmark {  background: transparent url(‘/assets/img/shared/checkmark-v2.svg’) no-repeat;  background-size: contain;  width: 14px;  height: 12px;}

Raster Images

What’s a raster image?

Most of the traditional image optimization techniques for the web are applied to the use of raster images. The term “raster image” is used to refer to image file formats that encode an image as a grid of pixels. File formats like JPEG, GIF, and PNG encode color and transparency information for each individual pixel in an image using three or four channels: RGB(A). Three of these are color channels (Red, Green, Blue) and the fourth corresponds to the “Alpha” channel (transparency). Most commonly, each channel encodes a value using 8 bits, or 256 possible values per channel. A combination of the three color channels yields 16,777,216 possible color values per pixel, sometimes referred to as “true color,” in part because the human eye can distinguish on the order of 10 million colors. “Bit-depth” or “color-depth” can refer either to the number bits used to encode color per channel or per pixel. Most standard JPEG images are classified as 8-bit or 24-bit JPEGs because they have three 8-bit color channels per pixel (JPEGs do not support transparency).

Note that because raster images encode information per pixel, the larger the dimensions of the image, the larger the image file. Doing the math, we can calculate the file size of a hypothetical JPEG. Suppose we have an image that is 100 pixels wide by 100 pixels high. Assume that each pixel encodes information using three channels and that there are 8 bits per channel. Because 8 bits is equivalent to 1 byte, it requires 3 bytes to per pixel to encode the information for the three channels. This equates to 30,000 bytes or 30 KB of space for this uncompressed image. Note that this is equivalent to about 10 pages of plain text (assuming about 500 words/3,000 characters per page). You could also say this picture is worth 5,000 words.

Raster Image Optimization.

Because raster images are often the largest assets that a web page includes, it is in our best interest to look for ways to reduce their file sizes using image compression. Image compression is a well-developed discipline that has produced algorithms that generally fall into two categories: “lossless” and “lossy”.

Lossless compression preserves all of the original pixel data while reducing file size. There are hard limits to how much you can losslessly compress an image because there is a fixed amount of pixel data that must be preserved. Lossy compression, on the other hand, allows for the preservation of varying degrees of pixel data. As such, lossy compression can be done much more aggressively and yield much smaller files. However, the degree to which you compress image files when using lossy compression must be balanced by the visual quality of the images and the appearance of unwanted visual artifacts. Typically, images will be compressed first using a lossless compression algorithm and then run through a lossy compression algorithm.

JPEG is a lossy format that lends itself to lossy compression and as such, is the defacto standard for optimized photographic images. The PNG file format was created to be a lossless image format, and so generally only offers limited file size savings when compressing. Generally, we might only use PNGs if we need a high quality image with transparency. Be wary of file sizes when using PNG.

Sizing your raster images.

For raster images, it is also important to use an image that is as close to its rendered dimensions on the website as possible. When an image’s dimensions are different from their final rendered dimensions on the web, it is up to the browser to resize that image. This increases the amount of time and computational resources necessary to render the page. Furthermore, if the image’s dimensions are larger than necessary, that means the time it takes for the browser to download them will be longer than necessary.

If you are building a responsive web site, it is important to use media queries to respond to changes in the rendered size of an image with image assets that are as close as possible to that rendered size.

It is also important to take into account screen resolution. A screen with high pixel density may have two or three physical pixels per virtual pixel. As such, an image twice or three times the dimensions (depending on the number of physical pixels/virtual pixel) should be served in order to avoid the appearance of visual artifacts.

This is all very nice, but how do I put this into practice?

Your mission, should you choose to accept it, is to reduce the file size of your raster images by resizing and compressing them.

  1. Start with an image and create resized versions of it that correspond to the rendered dimensions of the image at supported CSS breakpoints. Make sure to also take into account the screen resolution and serve proportionately larger images for higher resolution screens. For example, a device with a device pixel ratio of two should be served an image with dimensions twice as large.
  2. Media queries for screen resolution are becoming more standard, though still require a bit of finesse to get consistent behavior across browsers.
  3. View example usage of `min/max-device-pixel-ratio` and `device-pixel-ratio` media queries here.
  4. Compress. In general, the compression quality of a JPEG is tuned on a scale of 0 to 100. Don’t be afraid to compress aggressively and raise the quality when visual artifacts become obvious.
  5. If using Adobe Photoshop (v19.1.1) to export images, go to File > Export > Save for Web (Legacy)…
  6. This menu will allow you to tune the compression quality of the JPEG as well as change its dimensions while viewing a side by side comparison.

Note:

  • Another image attribute that can be adjusted to yield file size savings is chroma subsampling: the balance of color and luminescence information encoded in digital images. Because the human eye is much more sensitive to brightness than it is to color, changing the chroma subsampling ratio allows us to remove some color information without noticeably affecting the quality of the image.
  • In Photoshop, there is no option to adjust Chroma subsampling independently. Instead, it is adjusted automatically when compressing to a quality level below 51.

Got lots of images to optimize in a hurry? There’s a command line tool for that.

You may not want to resize and compress a large number of images one by one in Photoshop. Instead, you can optimize sight unseen using a handy command line tool. Google recommends ImageMagick convert. Instructions to download this tool can be found here. I found the MacPorts install fast and easy.

Google has an article that outlines their recommendations for using ImageMagick convert. Note that while google recommends dropping the image quality to 85, I’ve found that a lower quality factor can yield significant file size savings for little visual tradeoff. However, this is also dependent on image dimensions and screen resolution. From Google’s article:

- Reduce quality to 85 if it was higher. With quality larger than 85, the image becomes larger quickly, while the visual improvement is little.
- Reduce Chroma sampling to 4:2:0, because human visual system is less sensitive to colors as compared to luminance.
- Use progressive format for images over 10k bytes. Progressive JPEG usually has higher compression ratio than baseline JPEG for large image, and has the benefits of progressively rendering.
- Use grayscale color space if the image is black and white.

convert supports a wide array of conversion options, but it may be sufficient to use a command of the following form:

convert INPUT.jpg -sampling-factor 4:2:0 -strip [-resize WxH] [-quality N] [-interlace JPEG] [-colorspace Gray/sRGB] OUTPUT.jpg

For example:

convert puzzle.jpg -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB puzzle_converted.jpg

In the end, optimizing images for your web page is not exact science. I hope this article will have provided some insight into what should be considered and how to get started with some of the image optimization tools available. Here at TuneIn, we continue to iterate on our image optimization process and work toward automating as much of it as possible.

Happy image optimizing!

--

--