Portable Network Graphics: how lossless compression works
PNG uses lossless compression, so it loses nothing. The W3C specification defines lossless as a method of data compression that permits reconstruction of the original data exactly, bit for bit, and it names preserving all information through filtering and compression as a design goal. RFC 2083, the version 1.0 specification published in March 1997 under T. Boutell, calls the format an extensible file format for the lossless, portable, well-compressed storage of raster images. It describes PNG as a patent-free replacement for GIF that keeps features such as indexed color, transparency, and progressive display, and adds truecolor, grayscale, full alpha, and gamma information.
Lossless compression takes two steps here, and neither throws data away. The first is filtering. The encoder works through pass extraction, scanline serialization, filtering, compression, and chunking, and filtering is applied to bytes rather than pixels, whatever the bit depth or color type. Each scanline begins with a filter type byte. The W3C specification states plainly that the filter operation is deterministic, reversible, and lossless. RFC 2083 adds that the filter step itself does not reduce the size of the data; it only transforms the bytes so that the compressor has an easier time.
PNG defines five filter types. Each predicts a byte from neighbors already known to the decoder, then stores the difference, using arithmetic modulo 256 so that inputs and outputs fit into bytes. In the specification's notation the left neighbor is a, the pixel above is b, and the upper-left is c. Type 0, None, stores bytes as they are. Type 1, Sub, subtracts the byte one pixel to the left. Type 2, Up, subtracts the byte directly above. Type 3, Average, subtracts the floor of the average of left and above. Type 4, Paeth, subtracts whichever of the three neighbors is closest to left plus above minus upper-left, with ties broken in the order left, above, upper-left. RFC 2083 credits Alan W. Paeth for the filter and warns that the order in which ties are broken is critical and must not be altered.
Decoding runs the same predictor on bytes it has already reconstructed and adds back the stored difference. Sub adds the reconstructed left byte, and Paeth adds the Paeth prediction from reconstructed neighbors. Bytes to the left of the first pixel are treated as zero, as is the prior scanline for the first row. Because the arithmetic is exact, every byte comes back exactly as it went in. The libpng book chapter on compression says missing edge bytes are treated as zero rather than wrapping around, and that corresponding bytes are offset by the bytes per pixel, so that red is compared with red.
An encoder can choose a different filter for each row. Testing every combination is impractical, since a 20-row image would need over 95 trillion of them. The libpng book describes heuristics: palette images rarely benefit from filters, and grayscale images under 8 bits per sample usually use None. For deeper grayscale and truecolor images, a heuristic proposed by Lee Daniel Crocker in 1995 picks the filter with the smallest sum of absolute differences, and it is almost always beneficial. The book's example, 16million.png, is 48 MB raw and about 36 MB with compression but no filtering. With filtering it drops to 115,989 bytes, a total compression factor of 434.
The second step is deflate, the compression itself. Compression method 0 is deflate, derived from LZ77, with a sliding window of at most 32,768 bytes. The libpng book explains that deflate replaces repeated strings with length and distance pairs, then Huffman-codes the output, using fixed and dynamic codes and splitting the output into blocks. Incompressible regions can be stored raw instead of expanding, which the book notes LZW cannot do. PKWARE defined deflate in 1991 for PKZIP 1.93a beta. The data must be in the zlib format, with a method value of 8 and no preset dictionary. The zlib check value is computed on the uncompressed data, so the decoder can verify that what it inflated matches what was filtered.
The filtered scanlines form a single zlib stream, which the file splits across IDAT chunks. Chunk boundaries can fall anywhere in the stream and mean nothing to the decoder. Each chunk has a length, a four-letter type, data, and a CRC over the type and data, and the specification notes that the CRC is always present, even for chunks with no data. A PNG file begins with the eight bytes 137 80 78 71 13 10 26 10. This signature distinguishes a PNG datastream from other data and allows early detection of some transmission errors.
The standard covers more than one image. The W3C specification, Third Edition, defines the datastream for a lossless, portable, compressed individual computer graphics image or frame-based animation. A static PNG holds one image, and APNG adds animation with three extra chunk types. A decoder that does not know APNG ignores those chunks and displays the static image.
Lossless compression does not mean small. The libpng book reports that seven GIFs totaling 391,752 bytes became 366,343 bytes as PNG, and that JPEG-LS beat PNG by 5 to 11 percent on natural images while PNG won by large margins on artistic ones. Its author stresses that the samples are too small to be conclusive. What PNG's lossless compression guarantees is not size but fidelity: the pixels that go in are the pixels that come out.
- W3C, Portable Network Graphics (PNG) Specification, Third Edition — www.w3.org
- IETF, RFC 2083: PNG Specification version 1.0 — www.rfc-editor.org
- libpng.org, PNG: The Definitive Guide, Compression and Filtering — www.libpng.org