DEV Community

David Miller
David Miller

Posted on

What PNG's row filters actually do

PNG preserves its pixels through a sequence of reversible steps. Before compression, it can transform each row of image bytes so that the compressor has a more predictable pattern to work with. PNG calls that transformation a filter.

Take one row of an 8-bit grayscale image with byte values 100, 102, and 103. A filter called Sub can represent that row as 100, 2, and 1: the first value, followed by differences from the value immediately to the left. The decoder reverses the process, adding each difference to the value it has already reconstructed.

For a color image, the operation still works on bytes. Sub compares a byte with the corresponding byte of the previous pixel, such as red with red, rather than simply subtracting the byte directly before it. Another filter, Up, compares with the corresponding byte in the row above. PNG defines other prediction methods as well. Each row starts with a byte that tells the decoder which filter was used there.

Filtering does not shorten the row on its own. The filtered bytes then go through DEFLATE compression. A flat background or a repeated graphic pattern often gives the compressor useful repetition. A noisy photograph is less predictable and can produce a large PNG, even though no image detail was lost during PNG encoding.

The encoder can choose a different filter for each row. That is one reason two PNG files can decode to identical pixels yet have different file sizes. If you are exporting a screenshot with fine text, compare the displayed pixels and the file size after export. The filter affects the bytes on disk; it does not change what the PNG decoder reconstructs.

Top comments (0)