Optimizing PNG Images for Web

Web developers spend a lot of time trying to optimize files to make web pages load faster. Modern web applications often minify and bundle JavaScript and CSS for that purpose, but we often forget to optimize images for the best browsing experience. Everyone knows that JPEG are small, but do not retain the best quality. So, what about when you need the sharpness or the transparency PNG offers? Is it possible to enjoy the perks of a superior image format without sacrificing loading times? Yes it is!

Image Formats Compared

Portable Network Graphics (PNG) is a lossless image format meaning that it maintains the original colors and sharpness. When compared with JPGs, you can see that it does not produce the weird artifacts around the objects. It also handles transparency way better than GIFs which have a terrible rendition of the borders with the transparent pixels.

 JPG GIF  PNG
 Image Quality  Bad  Bad  Good
 Transparency  No  Bad  Good
 Image Size  Good  Bad  Bad

Lossy PNG

There are a few algorithms that can compress an image, but it is essential to maintain image quality while reducing file size. After trying a few options, I recommend pngquant which is a command line utility and a library for compressing PNG images.

pngquant takes a PNG and transforms it into a lossy PNG that looks virtually the same, but is around 70% smaller.

This tool is very useful because its available as a command and as a program with GUI for any OS. So it’s very easy to incorporate in automated tasks, or if you just want to optimize a few images, you can do it with your program of choice. For MacOS, I personally like pngyu for batch processing or ImageOptim

Find the pngquant project in Github

https://github.com/kornelski/pngquant

Original vs Compressed

For the following tests I used pngyu for MacOs.

Original Compressed
577Kb 163Kb

Results

If you zoom in 1:1, you will notice very soft dithering around the fur where it meets the transparent background. The rest of the body retains its sharpness and the gradients in the eyes look just like the original. Color rendition is good and no apparent compression artifacts appear around the sharp borders like the nose.

The compressed PNG is 70% smaller than the original while keeping most of the quality.

Conclusion

For the majority of images that require transparency, PNGs compressed with pngquant provide great quality and reduced file size. However, for very specific cases with subtle gradients dithering might be more noticeable, so the uncompressed image might be a better option.

Share Post :