PNG file format deep dive
I have a secret fascination with image compression formats. I think it started a year or two ago when someone at work uploaded a PNG image that looked rather large to me, and I asked them to compress the file first. At that point I knew about the standard compression tools like pngcrush and optiPNG, but didn’t know exactly how they worked. I then also became acquainted with Zopflipng which absolutely knocked it out of the park with that file and blew my mind. How do they all work, and how come this new algorithm from the fine people at Google can be so much better than the old ones? How is it even possible for the same image to have so many different representations within the exact same file format?
Structure of the PNG format
To understand the PNG format one needs to understand the structure of the binary file. The file consists of typed chunks. There are chunks for different kinds of metadata and color profiles, for example, and indeed the first thing that many optimizers do is to just ditch those extra chunks completely. Depending on how verbose the tool was that created the file, this already may yield great savings.
The actual image data, however, is located in IDAT chunks – short for “image data”. There may be as many or as few IDAT chunks in a PNG file as the encoding application wants, dictated by buffer lengths and such implementation details. The PNG format still supports only one image per file, so all the IDAT chunks still encode that one. The data may be cut between chunks at any point, and compression software may just combine these IDAT chunks into one to save a few bytes of checksums and chunk boundary data.
The Deflate algorithm
The image data encoding is where it actually gets interesting. PNG is a relatively simple format actually so it’s pretty easy to understand on a high level. The stream of pixel color values is compressed using the Deflate algorithm, which in turn consists of the LZ77 compression step and a Huffman encoding step.
LZ77
Wikipedia actually explains LZ77 quite well:
LZ77 algorithms achieve compression by replacing repeated occurrences of data with references to a single copy of that data existing earlier in the uncompressed data stream. A match is encoded by a pair of numbers called a length-distance pair
So for example to compress the string CATS AND DOGS AND CATSCATSCATS the result may be CATS AND DOGS[5,9][4,18][8,4]. The start is just literals for the algorithm to get some context, but once it starts seeing repeating strings, it starts replacing those with the length-distance pairs. To decompress it again, the [5,9] takes 5 characters from 9 characters back, i.e. AND. [4,18] then finds CATS and inserts that, at which point the reconstructed string looks like CATS AND DOGS AND CATS[8,4]. Now, finally, the algorithm takes 8 characters from 4 characters back, which shouldn’t be possible but is, because the algorithm keeps inserting new context for itself to fill the missing info, yielding the final CATSCATS.
This should give you the first clue on why there can be different binary representations: the Deflate algorithm could have encoded the ending as [4,4][4,4] just as well, but [8,4] is a shorter way of saying the same if your algorithm is clever enough. The LZ77 implementation needs to make decisions on how far to look back (not further than 32 KiB) and how long matches to pick, and a greedy algorithm that always picks the first and easiest solution that it encounters certainly may not be the most optimal one. (By “optimal” I mean the best compression ratio, but you could also optimize by other variables like compression time, and then you’d get different results.)
Huffman encoding
After the LZ77 step the Deflate algorithm moves on to the Huffman encoding step. Here, the results of the LZ77 compression are compressed even further by creating a table of variable-length codes so that the more frequently occurring symbols get a shorter code and rarely occurring symbols get a longer code.
Say the LZ77 step gave us ASD[4,2]QWASD[4,2]QWEASD. Each letter is a literal byte, and each [4,2] says โcopy 4 bytes from 2 bytes back.โ Deflate uses one Huffman table for literals, match lengths, and the end-of-block marker, and another for match distances. One possible set of codes is:
Literals and lengths:
00=A 010=D 011=Q 100=S 101=W
110=length 4 1110=E 1111=end of block
Distances:
0=distance 2
So ASD[4,2] starts the bitstream with 00 100 010 110 0. The first three codes give us A, S, and D. Then 110 tells the decoder to copy four bytes, so it switches to the distance table to read the next 0.
The codes above add up to 52 bits for the whole sequence, including the end-of-block marker (but ignoring the overhead needed to describe the Huffman tables themselves). Now try writing out SDSD instead of using [4,2], both times it appears. With the same table, each SDSD takes 12 bits instead of 4, bringing the total to 68 bits. But now S and D each occur seven times instead of three, so we can build a new Huffman table that gives them shorter codes. With that table, the total drops to 57 bits. The back-references still win in this example, just not by as much as the first version made it look.
Pixel data encoding
So, now we know: a PNG encoder runs an LZ77 compression and a Huffman algorithm over the pixel data. But what does the pixel data then look like?
Assuming a full color image and not a palettized one, each pixel consists of a byte for a red, green, and blue color channel value, so three bytes (assuming no alpha channel for transparency, which would just be a fourth byte). A fully red pixel would thus be encoded as FF 00 00.
Scanlines and filters
The pixels are encoded sequentially from left to right and from top to bottom. Each row of pixels is called a scanline, and each scanline begins with a filter byte, which defines the filter to be used. Filters can change how the pixel values are encoded, and there are five filters for the encoder to choose from for each scanline.
A SUB filter takes the pixel to the left from the current one and only encodes the difference to that one. Filtering takes place color channel per color channel, so the red value of the previous pixel is used to predict the red value of the current pixel, green value for the green, and blue for the blue. Thus if your first pixel is a nice orange like “FF 88 00” and the next one is ever so slightly different orange “FF 89 01”, using the SUB filter it would become “00 01 01”, which, the theory goes, has less entropy and thus would compress much better in the LZ77 step that follows.
Besides SUB, there are filters known as NONE, UP, AVERAGE, and PAETH. The NONE filter is exactly what it says: the bytes as-is, with no prediction. While this keeps the original entropy, it’s often not too bad for LZ77 anyway: the compression algorithm doesn’t care if it sees repeating bytes like “FF 38 1E FF 38 1E FF 38 1E” or “00 02 01 00 02 01 00 02 01”, as long as it can just find many long, repeating patterns!
The UP filter works just like SUB, but instead of using the left pixel as its predictor it uses the pixel above the current one.
AVERAGE uses, you might have guessed it, the average value of left and up pixels as the predictor. The PAETH filter, named after Alan W. Paeth, is the trickiest but still not too difficult to understand once you play it back. It takes three pixels: the one to the left (call it a), the one above (b), and the one to top left (c). It then calculates values like this, where p is the initial prediction and the latter values are distances from that to the individual values:
p = a + b - c
pa = abs(p - a)
pb = abs(p - b)
pc = abs(p - c)
Let’s say we’re predicting the value of x here; it may be any color channel. This table represents a 2x2 grid of pixels:
| c=100 | b=70 |
|---|---|
| a=125 | x |
Now, p=125+70-100=95, pa=abs(95-125)=30, pb=abs(95-70)=25, and pc=abs(95-100)=5. The lowest of these values is 5 for pixel c, so the value of c, 100, will become the predictor, and the actual value of x will be encoded as “x - 100” modulo 256.
These different filters then work the best for different types of images: think ones with large uniform blocks of colors, horizontal gradients, vertical gradients, noisy images, etc. Also, like mentioned, each scanline may even have a different filter for optimal compression performance.
Caveat
Even an image that’s just 32 pixels tall, say, a ๐ emoji, already has 5^32 possible per-scanline filter combinations. If your computer tested one combination in 1.4 nanoseconds, it would take it a million years to test them all!
Heuristics
This, then, is where heuristics come into play. It’s important to understand, however, that the PNG compression works as a whole: filter selection, LZ77, and Huffman encoding. Change anything upstream and you will affect what happens downstream. It is actually dirt cheap to do local optimizations for the per-scanline filters: for an image 32 pixels tall you could just test 32*5=160 different filters, if you have a heuristic for how good each filter is for a row.
Traditionally, minimum sum of absolute residuals has been a popular heuristic. Despite the mouthful of a name it’s trivial: interpret the filtered bytes as signed values and sum their absolute values! This would then favor rows with small values, while not over-penalizing the occasional larger value. For example, a scanline with the values 0+3+1+0+0+1+8+0 would have the sum of 13. Pick the filter whichever yields the lowest sum.
Another classic heuristic is to measure the entropy of the filtered bytes. This approach would reward a filter that can produce fewer unique values, as byte streams with less entropy tend to compress better than streams with a lot of noise.
Tests
Circling back to the beginning, Zopfli is an implementation of the Deflate algorithm by Google. It’s slow compared to other Deflates, but it uses that time to optimize the heck out of the LZ77 and Huffman steps. The Zopflipng app runs the Zopfli algorithm for PNG images and, by default, I thought it just tries to set all the scanlines to use the same filter with each other, i.e. it tests just five different filter combinations: all NONE, all SUB, etc.[ยน](#zopflipng manpage) This made me wonder, though, whether one could achieve even better compression by optimizing the filters for each scanline? (I later found out it does try some simple heuristics as well…)
For these tests I vibe-coded an app to do the Zopflipng compression for various images with various filter selection strategies. I also made it output statistics about the images to better explain why some filter configurations work better than others. The app has a GitHub workflow that publishes the results on GitHub Pages.
There’s a corpus of test images I’ve created in different ways, and the app runs tests on all of them. The tests consist of different filter selection strategies: it of course tests the trivial cases of just using the same filter, each of the five options, on all the rows of an image. Then there’s the entropy minimizer, and a few others like adaptive, which minimizes the residuals; I even had Chad create me a genetic algorithm that attempts to breed a successful filter combination for each image.
However, I found the raw data of bytes and percentages rather cumbersome to interpret, so the app also reports a human-readable summary for each image based on its findings.
Take, for example, the icon of my Gunzip application I wrote about earlier:

The minimum entropy for this image is achieved with this kind of filter combination, where the color of each row indicates the filter used on that row; red: NONE, orange: SUB, blue: UP, green: AVERAGE, purple: PAETH:
![]()
Possibly a more interesting case study could be this image of Pestilence from my NetHack bestiary:

The app has determined that fixed-up is the best strategy, i.e. have all scanlines defined by the UP filter. This means the value of each pixel is compared to the value immediately above it. Here’s the full analysis it gives for this result; it’s rather technical, but given what you should now know about how the compression works, it should be understandable:
Winning strategy: fixed-up beat entropy by a moderate margin of 93โ084 bytes (5.73% smaller).
Likely explanation: PAETH minimizes local residual magnitude. Directional smoothness is balanced across axes. The genetic search converged to the same filter sequence as fixed-up, independently rediscovering the identical filtered stream. Compared with entropy, fixed-up produces dramatically more repeated DEFLATE-friendly 32-byte substrings (65162 vs 37741), affecting global repeat structure. fixed-up outperforms PAETH overall because stronger global repetition dominates local residual minimization for final DEFLATE size.
Compression insight: PAETH minimizes local residuals, but simpler predictors create a more regular DEFLATE-friendly residual language. This suggests global phrase reuse matters more than per-pixel predictor cleverness for this image.
Compression observations:
- The result provides clear evidence that a mostly uniform predictor strategy is more valuable than locally optimal prediction because it keeps the residual vocabulary stable.
Similar results can be seen across other images as well: a fixed filter strategy performs surprisingly well. Consistency often beats cleverness. The “residual vocabulary” above basically means the byte values and recurring byte patterns that are passed to the Deflate algorithm, which then finds and reuses those patterns. Different filters are likely to produce lines that look different too, whereas keeping the same filter produces broadly similar results which are easier for the compression phase.
Now, the best strategy for this image of Pestilence was fixed-up. Intuitively, you’d think that if you rotated this image 90 degrees counter-clockwise, the new best strategy would be fixed-sub (which compares the value of each pixel to that to its left), as it would then use the same comparisons, just in a different orientation. Much to my delight, when I created the rotated test image and ran the app, it worked exactly as I had thought and fixed-sub prevailed! (Only now the later versions of the app can find a very slightly better filter configuration using the genetic algorithm.)
Conclusion
We’ve seen how the choice of filters affects how well the PNG files are compressed. I was surprised to see how often consistency beat cleverness: micro-optimizing the filter for each scanline breaks the greater structure needed for an efficient round of Deflate compression. Everything you do upstream (the filters and choosing the color space) affects what happens downstream (Deflate). Depending on the file, a bad choice of filters by your software can, in the worst case, even double your file size.
However, note that the authors of Zopflipng themselves are the first to admit that to gain proper savings in image compression you should just switch to a more modern format like WebP instead of burning CPU cycles trying to optimize PNG images to the limit. ๐
(Pro tip: use the <picture> HTML element with multiple <source> elements and a fallback <img> element to offer the user’s browser a choice between multiple image formats!)
I’m still quite happy for this little experimenting project of mine. I don’t think I have, for example, ever actually seen those filter choices visualized like I did here. It’s a nice way of making this otherwise rather abstract subject more concrete. And who knows, maybe in the future I’ll learn how the WebP format works, too.