Webpage and image optimization howto

Date: May 2, 2019

This work-in-progress page is about optimizing webpages including images for faster downloads and resource savings.

  1. Image optimization

Image optimization

There are only three image formats to choose from: PNG, JPEG, and WebP.

To reduce PNG filesize, first use pngquant to reduce the color depth. Then, squeeze additional bytes using zopflipng. For example to reduce a PNG to 32 colors and compress it with zopflipng:

$ pngquant -s 1 -o example.png 32 example.png.orig
$ zopflipng example.png example2.png
$ ls -lS example* | awk '{print $5, $9}'
68169 example.png.orig
19663 example.png
17116 example2.png

The resulting image is visually indistinguishable from the original but only 25% of the original size.

To reduce JPG filesize, first open the file in a graphics editor such as GIMP or Photoshop and reduce the color depth until you can tell a difference in quality. Then save the file at 1 point above that level. Next, remove any metadata with jhead using the command jhead -purejpg example.jpg.

For WebP images, use cwebp. If the resulting WebP file size is lower than the source PNG or JPG, you can use both in HTML5 with the following example code:

  <source type="image/webp" srcset="example.webp">
  <img src="example.png" alt="example image">

Here, the browser will load the WebP image if and only if it supports WebP. Otherwise the browser will download and display the PNG image. Learn much more about HTML5 images using WebP and the picture tag.