Compression

PNG Compression

Lossless image compression format with support for transparency using the DEFLATE algorithm.

PNG and the limitations of GIF

In the early World Wide Web, GIF kept simple website graphics small and supported animation. It had two limitations that led to the development of another format. Its palette contained at most 256 colors, so it could not represent photographs with high color fidelity. Its LZW compression algorithm was covered by patents, and licensing demands created legal uncertainty for software developers.

In response, a group of developers created an open standard intended as a patent-free replacement for GIF. They named it PNG, short for . The design combined lossless compression, truecolor images, progressive display, and a full alpha channel. The format has a streaming structure based on data blocks called chunks. The IHDR chunk describes the image, IDAT chunks carry compressed data, and IEND marks the end of the datastream. Chunks can be processed in sequence without loading the complete image into memory. A CRC can detect corruption in a chunk. These properties make PNG suitable for graphics with sharp edges, text, and transparency.

DEFLATE in the PNG structure

JPEG can use lossy quantization in a multi-stage process, while PNG preserves the image data without loss. After filtering, PNG stores its scanlines in a zlib stream that uses the DEFLATE format. PNG compression method 0 uses the zlib stream and a DEFLATE window of up to 32 KiB. IDAT chunks contain consecutive pieces of one stream, while the zlib wrapper has its own integrity data, including an Adler-32 check value. DEFLATE combines LZ77-style repeated-sequence references with Huffman coding. The same data format is used inside ZIP and GZIP containers, which provide their own surrounding structures.

Part 1: LZ77 references to repeated data

The first stage of DEFLATE uses the to find repeated data in the recent input. In DEFLATE, a reference contains the match length and the distance to its earlier occurrence. The actual stream represents these values with length and distance codes, so the two-number reference is an instructional model.

The encoder reads image data byte by byte and maintains a "sliding window" of recently processed data. This window acts as a dictionary. For new bytes, the encoder checks whether the same sequence already appears in the window, which can be up to 32 KiB in DEFLATE. A distance cannot reach outside that window, and a match can copy bytes from the region currently being reconstructed. The compressor can still choose a literal when a match is too short or when encoding the reference would cost more bits.

  • If the sequence is new, the encoder writes it as a "literal" byte and advances the window by the written bytes.
  • If the sequence has appeared before, the encoder writes a reference instead of another copy. The reference contains two numbers:
    1. Distance: The number of bytes from the current position back to the match in the window.
    2. Length: The number of bytes copied from that match.

For example, consider the sentence: "The slow brown fox jumps over the other slow brown dog." In this character-level model, when the second "slow brown " is reached, a reference can have the form (distance: 36, length: 11), including the trailing space and counting distance in characters from the start of the current match to the start of the earlier match.

  1. It writes the beginning of the sentence as literals and adds those bytes to the window.
  2. At the second "slow brown ", it finds the earlier match and writes a reference instead of the 11-character match.
  3. It then writes "dog." as literals.

This technique works well for computer-generated graphics, which often contain large areas of one color or repeating patterns.

Part 2: Huffman coding for the resulting stream

The LZ77 stage produces a stream of literal bytes and length/distance references. The second DEFLATE stage represents these symbols with .

Huffman coding is entropy coding. The encoder measures how often literals and length or distance codes occur, then builds a codebook where:

  • Symbols that appear frequently receive shorter binary codes.
  • Symbols that appear infrequently receive longer binary codes.

Shorter codes for frequent symbols reduce the size of the stream. DEFLATE can use fixed Huffman tables for a block or tables described inside that block. LZ77 references and Huffman coding together form the lossless compression stage used by PNG.

Filtering scanlines before compression

DEFLATE benefits from repeated values. Natural images can contain noise and gradients that break long sequences of identical bytes. PNG therefore applies a reversible filtering step that prepares image data for compression.

The PNG encoder processes one horizontal row of pixels at a time, called a "scanline." Before compression, it can transform the row with a filter. This is not a visual effect. It is a reversible mathematical transformation that replaces scanline bytes with differences. Adjacent pixels often have similar values, so the differences contain more repetition and give DEFLATE a better input. PNG filters operate on bytes regardless of bit depth or color type.

For each scanline, the encoder can choose one of five filter types. The choice belongs to the encoder, and the filter type is stored as a filter byte before the filtered bytes so the decoder can reconstruct the original data. The encoder may compare a simple score for each candidate, but the PNG format does not require one selection heuristic. The filter types are:

  • Type 0: None: No filtering is applied. The scanline's raw bytes go directly to the compressor.
  • Type 1: Sub: Each byte is replaced by the difference between it and the byte for the preceding pixel in the same row. This suits smooth horizontal gradients.
  • Type 2: Up: Each byte is replaced by the difference between it and the corresponding byte in the previous scanline. This suits vertically repeating patterns.
  • Type 3: Average: Each byte is replaced by the difference between it and the floor of the average of the byte to its left and the corresponding byte in the previous scanline. This can help with diagonal gradients.
  • Type 4: Paeth: The filter predicts a value from the left, above, and upper-left bytes. It chooses the neighbor closest to the prediction and stores the difference from that neighbor. This can help with complex two-dimensional patterns while remaining exactly reversible.

Filtering does not reduce the number of bytes by itself. It prepares scanlines so that DEFLATE can use their repeated values more effectively. For the Sub filter, the preceding element is offset by the number of bytes per pixel, and the missing neighbor at the first pixel is zero. The gain depends on the image content.

PNG color modes and transparency

PNG supports several image types and two ways to represent transparency. The color type and bit depth determine the samples stored for each pixel. The standard distinguishes grayscale, truecolor, indexed color, and variants with an additional alpha sample.

Color modes

PNG defines several modes for different kinds of images:

  • Grayscale: One luminance channel can use 1, 2, 4, 8, or 16 bits per sample.
  • Indexed Color: Each pixel stores a palette index with a depth of 1, 2, 4, or 8 bits. The palette can contain up to 256 entries, so this mode suits images with few colors.
  • Truecolor: Each pixel stores red, green, and blue samples. With 8 bits per sample, this gives 24 bits per pixel and about 16.7 million color combinations. PNG also permits 16 bits per sample, or 48 bits per RGB pixel. Truecolor with alpha adds a fourth sample at the same depth.

Alpha channel and transparency

PNG supports a full . Grayscale-alpha and truecolor-alpha modes store the additional sample with each pixel. GIF represents transparency through a palette color, while PNG can store intermediate opacity values for 8- and 16-bit alpha samples. Indexed color can also use a tRNS table for simple transparency without a full alpha channel.

When an alpha channel is present in Grayscale or Truecolor mode, each pixel receives an additional 8 or 16-bit sample. The sample describes opacity. For 8-bit alpha, 0 means fully transparent and 255 fully opaque. For 16-bit alpha, the range is 0 to 65535. This representation supports anti-aliased edges, fading shadows, and graphics placed over different backgrounds.

Related articles