Image Compression For High DPR Images

Images typically account for 40% of the size of a webpage. This makes them a key thing to look at when optimising a site. Image optimisation typically involves resizing and compressing it to be as small as possible; but the trick is to do so without turning it into a blocky mess.

The days of manually compressing images are long gone. In the case of a CMS images are uploaded by users who don't (and shouldn't need to) care about things like compression. Libraries are now used to automate this. We reach for Imagick and league/glide, and this combination makes it really easy to resize, crop, re-encode, compress, etc, etc.

When Two Becomes Four

An issue presents itself when we want to generate images for devices which have a DPR above 1. AKA mobile devices. Glide makes this easy you set the dpr parameter to 2 and just walk away. Not so fast, literally. A 2x DPR image has 4 times as many pixels, this means it takes longer to process. For small images the difference is small. Larger images can have an unacceptable delay and lead to server timeouts.

A second problem is the file size. You don't get 4 times as many pixels for free, the image will be larger, much larger. This is exactly what we were trying to avoid.

The solution to both problems is simply to increase the compression. When the pixel density is higher compression can be more aggressive without introducing any perceivable visual change. In my testing I found you could more than halve the quality setting and get a comparable image.

Before

  • File size: 423 kB
  • Dimensions: 2560x721
  • Quality: 80

After

  • File size: 167 kB
  • Dimensions: 2560x721
  • Quality: 30

Photo by Niklas Weiss on Unsplash

The more aggressive compression throws away nearly 60% of the data but the image looks almost the same to our eyes. It must be said that the level of compression you can get away with depends on the contents of the image

The above examples uses the JPEG encoding but the same applies to other encodings:

  • AVIF becomes 6.2 times smaller (454 kB vs 73 kB)
  • Webp becomes 2.3 times smaller (342 kB vs 146 kB)

We Need To Go Deeper!

If you want more information on this I recommened reading Jake Archibald's article on the same subject.

UPDATE: We recently wrote a tool which can automatically determine the compression level for any image. Read about it here

Popular Reads

Subscribe

Keep up to date

Please provide your email address
Please provide your name
Please provide your name
No thanks