DEV Community

Farai Gandiya
Farai Gandiya

Posted on • Originally published at codelab.farai.xyz on

How I Optimize PNGs

How I Optimize PNGs was first published on Farai's Codelab.


Here’s how I optimize images in three steps:

  1. Resize the image using ImageMagick to the desired sizes. The size I usually convert to is a 240px width image for small screen devices like feature phones that fit the media query of (max-width: 400px) and (-webkit-device-pixel-ratio: 1).
    • If it’s a non-photogenic image inside a JPEG, I convert the image sizes to PNG using it.
    • If I’m converting an SVG, I use Inkscape (specifically inkscape-cli) since it’s very good at rendering SVGs.
  2. Use CompressPNG.com to restrict the color palette as much as I can using a slider. This makes a massive difference in file sizes.
  3. Finally, I then use ZopfliPNG to recompress the PNG for a slight size reduction. PNGs use some sort of DEFLATE compression algorithm to compress all the image data—Zopfli is a very good, but slow implementation of DEFLATE. It’s a ~7% reduction which is just a handful of kilobytes.
  4. Depending on the file size reduction and quality, I might also convert it to WebP or AVIF. This isn’t as common since PNGs ae really good at non photographic images.

This process is based on my naive understanding of how PNGs work. I want to make a comprehensive post on how PNGs work and on how to use that understanding to better compress PNGs. There’s a lot about the compression techniques, color indexing, sampling and the like.

Glossary

non-photographic image—not a photo like illustrations, graphics and diagrams.


Thanks for reading! If you liked this post, consider supporting my work by:

Discussion (2)

Collapse
idarek profile image
Dariusz Więckiewicz

I did small experiment recently, as all my PNG images are optimised via imagecompressor.com, some of them with custom number of colours, I convert them to WebP W 75% and see in 90% file reduction.

As all people are hyped with AVIF, I haven’t.

I do bulk conversion to AVIF q10-30 to see NO improvement.

AVIF supposed to be smaller than WebP but mostly it’s not longer bigger than WebP, in 90% of cases was even larger than Optimised PNG.

It took WebP some time for popularisation and I think for AVIF is a bit too early and once all will used WebP along other fallback formats, maybe till that time AVIF will evolve to useable state.

Collapse
idarek profile image
Dariusz Więckiewicz

Re: -WebKit (as well as -moz) what’s the sense of using it in in 2021? Where all browsers dealing with native behaviour and don’t need that?