Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Image files: PNG, JPEG and Netpbm

ProblemStore raster images losslessly (PNG, with its DEFLATE compression, and the plain Netpbm formats) and compactly with controlled loss (baseline JPEG)
Devised byThomas Boutell and the PNG group (1996); Phil Katz (1993), DEFLATE; Jef Poskanzer (1988), Netpbm; the Joint Photographic Experts Group (1992), JPEG; Nasir Ahmed (1974), the DCT
AccuracyEvery PNG and Netpbm variant written by Pillow decodes identically, and Pillow reads the library’s files identically; JPEG quality matches Pillow’s within 0.1 dB at the same size (tables below)
Cost for each; the DEFLATE encoder’s hash-chain search grows with the compression level
Read firstDiscrete cosine and sine transforms, Entropy coding: Huffman, Shannon-Fano and arithmetic coding
APIpng_decode, png_encode, RasterImage, read_png_file, write_png_file, ppm_decode, ppm_encode, jpeg_encode, jpeg_decode, JpegImage, read_jpeg_file, write_jpeg_file, zlib_compress, zlib_decompress, inflate, deflate

Overview

Image files trade size against fidelity in three ways.

  • Netpbm files (PBM, PGM, PPM) are a text header and the raw samples. They are trivial to read and write, and large.
  • PNG is lossless. Each row is first transformed by a filter that predicts each byte from its neighbours, which turns smooth images into small numbers, and the result is compressed with DEFLATE, the algorithm of zip and gzip.
  • JPEG is lossy. It transforms 8×8 blocks with the discrete cosine transform, quantises the coefficients (coarsely at high frequencies, where the eye is least sensitive), and entropy-codes the result. It typically stores a photograph in a tenth of the raw size with little visible change.

The library reads and writes all three. The image-processing chapter uses its PNG writer for every figure with pictures in it.

Where it is used

Reading and writing image files connects the image-processing chapters to real pictures.

  • Photographs and scientific images. PNG stores them losslessly (microscopy, astronomy, medical figures); JPEG stores photographs compactly.
  • Computer vision. Datasets, camera frames and test images are loaded, processed (filtered, segmented, matched) and written back out.
  • Plots and figures. Netpbm formats are simple enough to produce from any program without a library.

History

Jef Poskanzer created the portable bitmap formats in the late 1980s as a lowest common denominator for converting between image formats. PNG was designed in 1995, after Unisys began enforcing its patent on the LZW compression in GIF. Thomas Boutell’s first draft became a W3C recommendation in 1996, built on Phil Katz’s patent-free DEFLATE (1993), which pairs Lempel–Ziv matching (1977) with Huffman coding (1952). JPEG came from the Joint Photographic Experts Group, standardised in 1992, building on Nasir Ahmed’s discrete cosine transform (1974). Its baseline profile, sequential 8-bit Huffman-coded DCT, is still the most used image format in the world.

The idea

PNG and DEFLATE

A PNG file is a signature and a series of chunks (IHDR for the header, PLTE for a palette, IDAT for the compressed data, IEND), each with a CRC-32 checksum. Before compression, each row is filtered with one of five predictors. A byte is coded as its difference from the byte to the left (), above (), their average, nothing, or Paeth’s predictor: whichever of , and the upper-left byte is closest to . The encoder picks, for each row, the filter whose output has the smallest sum of absolute values, the heuristic recommended by the standard. Decoding reverses the filters:

fn paeth(a: u8, b: u8, c: u8) -> u8 {
    let p = a as i16 + b as i16 - c as i16;
    let (pa, pb, pc) = ((p - a as i16).abs(), (p - b as i16).abs(), (p - c as i16).abs());
    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

/// Reverses the scanline filters of one (sub-)image of `rows` rows of `stride` bytes.
fn unfilter(data: &[u8], rows: usize, stride: usize, bpp: usize) -> Result<Vec<u8>, ErrorsJSL> {
    if data.len() < rows * (stride + 1) {
        return Err(corrupt("PNG image data is truncated."));
    }
    let mut out = vec![0u8; rows * stride];
    for y in 0..rows {
        let filter = data[y * (stride + 1)];
        let line = &data[y * (stride + 1) + 1..(y + 1) * (stride + 1)];
        let (done, current) = out.split_at_mut(y * stride);
        let previous = if y > 0 { &done[(y - 1) * stride..] } else { &[][..] };
        let current = &mut current[..stride];
        for i in 0..stride {
            let a = if i >= bpp { current[i - bpp] } else { 0 };
            let b = if y > 0 { previous[i] } else { 0 };
            let c = if y > 0 && i >= bpp { previous[i - bpp] } else { 0 };
            let predictor = match filter {
                0 => 0,
                1 => a,
                2 => b,
                3 => ((a as u16 + b as u16) / 2) as u8,
                4 => paeth(a, b, c),
                _ => return Err(corrupt("Unknown PNG filter type.")),
            };
            current[i] = line[i].wrapping_add(predictor);
        }
    }
    Ok(out)
}

The decoder handles every colour type (greyscale, RGB, palette, each with or without alpha) at every bit depth, palette transparency and Adam7 interlacing. Low bit depths are scaled to 8 bits, and 16-bit images stay 16-bit.

DEFLATE replaces repeated strings by (length, distance) references to earlier text, up to 32 KiB back. It then codes literals, lengths and distances with Huffman codes. The library’s encoder finds matches with hash chains: each position is filed under a hash of its next three bytes, so earlier occurrences of the same three bytes are linked in a list, searched further at higher levels. It writes them with DEFLATE’s fixed Huffman code, and falls back to stored blocks when compression would expand the data. Without that fallback, random data grows by about 6%. The decoder handles all three block types, including dynamic Huffman codes.

fn deflate_fixed(data: &[u8], level: u8) -> Vec<u8> {
    const WINDOW: usize = 32768;
    const HASH_BITS: u32 = 15;
    let max_chain = 4usize << level.min(9);
    let hash = |i: usize| -> usize { (((data[i] as u32) << 16 | (data[i + 1] as u32) << 8 | data[i + 2] as u32).wrapping_mul(2_654_435_761) >> (32 - HASH_BITS)) as usize };
    let mut head = vec![usize::MAX; 1 << HASH_BITS];
    let mut previous = vec![usize::MAX; data.len()];
    let mut writer = BitWriter::new();
    writer.bits(1, 1); // final block
    writer.bits(1, 2); // fixed Huffman
    let mut i = 0;
    let insert = |head: &mut Vec<usize>, previous: &mut Vec<usize>, k: usize| {
        if k + 2 < data.len() {
            let h = hash(k);
            previous[k] = head[h];
            head[h] = k;
        }
    };
    while i < data.len() {
        let (mut best_length, mut best_distance) = (0, 0);
        if i + 2 < data.len() {
            let mut candidate = head[hash(i)];
            let mut chain = 0;
            while candidate != usize::MAX && i - candidate <= WINDOW && chain < max_chain {
                let limit = (data.len() - i).min(258);
                let mut length = 0;
                while length < limit && data[candidate + length] == data[i + length] {
                    length += 1;
                }
                if length > best_length {
                    best_length = length;
                    best_distance = i - candidate;
                    if length == limit {
                        break;
                    }
                }
                candidate = previous[candidate];
                chain += 1;
            }
        }
        if best_length >= 3 {
            write_match(&mut writer, best_length, best_distance);
            for k in i..i + best_length {
                insert(&mut head, &mut previous, k);
            }
            i += best_length;
        } else {
            fixed_literal(&mut writer, data[i] as usize);
            insert(&mut head, &mut previous, i);
            i += 1;
        }
    }
    fixed_literal(&mut writer, 256);
    writer.finish()
}

Table 26.6. DEFLATE compressed sizes of the library against zlib.

databyteslibrary, level 6 / 9zlib, level 6 / 9
photograph pixels4915244424 / 4439641509 / 41461
English text450090 / 9080 / 80
random bytes50005011 / 50115011 / 5011

zlib does 7–13% better on compressible data because it builds a Huffman code for each block from that block’s symbol frequencies, and defers a match by one byte when the next position has a longer one (“lazy matching”). The library’s fixed code is simpler, and all its output is valid zlib.

Baseline JPEG

  1. Convert RGB to : brightness and two colour differences.
  2. Cut each component into 8×8 blocks and take the two-dimensional DCT of each, which concentrates a smooth block’s energy in a few low-frequency coefficients.
  3. Divide each coefficient by an entry of a quantisation table and round. Higher frequencies get larger divisors, and the tables are scaled by the quality setting.
  4. Code the DC coefficient as its difference from the previous block’s. Read the AC coefficients in zig-zag order, from low to high frequency, and code them as (run of zeros, value) pairs.
  5. Huffman-code everything with the standard tables of the JPEG specification’s Annex K.
fn fdct(block: &[f64; 64]) -> [f64; 64] {
    let c = dct_basis();
    let mut tmp = [0.0; 64];
    for y in 0..8 {
        for u in 0..8 {
            tmp[y * 8 + u] = (0..8).map(|x| block[y * 8 + x] * c[x][u]).sum();
        }
    }
    let mut out = [0.0; 64];
    for u in 0..8 {
        for v in 0..8 {
            out[v * 8 + u] = (0..8).map(|y| tmp[y * 8 + u] * c[y][v]).sum();
        }
    }
    out
}

The encoder writes 4:4:4 (no chroma subsampling) with the Annex K tables scaled by the IJG quality formula. That is libjpeg’s convention too, so the library and Pillow at the same quality make files of almost the same size and quality:

Figure 26.2. JPEG rate.

qualitylibrary (4:4:4)Pillow (4:4:4)
202930 bytes, 25.35 dB2930 bytes, 25.35 dB
504606 bytes, 28.36 dB4621 bytes, 28.36 dB
9010435 bytes, 35.54 dB10487 bytes, 35.45 dB

Chroma subsampling (4:2:0, Pillow’s default) stores colour at half resolution. At the same quality setting it saves 13–22% of the bytes here. PSNR, which weighs colour errors like brightness errors, rates it no better at equal size; its advantage is perceptual, because the eye resolves colour less finely than brightness. The library’s decoder accepts any subsampling, custom tables and restart intervals. It upsamples chroma as libjpeg does, interpolating linearly between chroma sample centres: for 2:1 factors that weights the nearer sample and the farther in each direction. Plain replication of the chroma samples would decode up to 82 levels away from libjpeg at colour edges and 0.6 dB worse in PSNR; with interpolation the decodes agree to within 2 levels.

    // A subsampled component is interpolated linearly between its sample centres, as libjpeg's
    // "fancy" upsampling does: for 2:1 that weights the nearer sample 3/4 and the farther 1/4 in
    // each direction (9/3/3/1 sixteenths for 2:1 both ways). Samples beyond the component's
    // edge repeat the last one.
    let sample = |c: &Component, x: usize, y: usize| -> f64 {
        let (rh, rv) = (hmax / c.h, vmax / c.v);
        if rh == 1 && rv == 1 {
            return c.plane[y * c.plane_w + x];
        }
        let (cw, ch) = ((width * c.h).div_ceil(hmax), (height * c.v).div_ceil(vmax));
        let at = |i: isize, j: isize| c.plane[(j.clamp(0, ch as isize - 1) as usize) * c.plane_w + i.clamp(0, cw as isize - 1) as usize].clamp(0.0, 255.0);
        let u = (x as f64 + 0.5) / rh as f64 - 0.5;
        let v = (y as f64 + 0.5) / rv as f64 - 0.5;
        let (i, j) = (u.floor(), v.floor());
        let (fu, fv) = (u - i, v - j);
        let (i, j) = (i as isize, j as isize);
        (1.0 - fv) * ((1.0 - fu) * at(i, j) + fu * at(i + 1, j)) + fv * ((1.0 - fu) * at(i, j + 1) + fu * at(i + 1, j + 1))
    };

Progressive, arithmetic-coded, 12-bit and multi-scan files are refused with an error.

Netpbm

A Netpbm header is a magic number (P1 to P6), the width, height and (except for bitmaps) the maximum value, separated by whitespace, with # comments allowed. The samples follow as ASCII numbers (P1–P3) or raw bytes (P4–P6, 16-bit big-endian when the maximum exceeds 255). Bitmaps store 1 for black, and are read as 8-bit greyscale with black 0 and white 255.

Reading and writing other programs’ files

Files written by Python’s libraries, read by this one:

Table 26.7. Image files written by Python and read by the library.

file written by Pythonbytesread by the library
png grey635identical
png RGB1866identical
png grey + alpha1237identical
png RGBA2517identical
png palette360identical
png palette + tRNS376identical
png 1-bit136identical
png 16-bit1540identical
ppm P62317identical
pgm P5781identical
pbm P4105identical
ppm P3 (text)8223identical
pgm 16-bit1551identical
jpeg 4:4:41318PSNR 30.3 dB against the original (Pillow: 30.3 dB)
jpeg 4:2:01014PSNR 25.1 dB against the original (Pillow: 25.1 dB)
jpeg 4:2:0 with restarts933PSNR 24.7 dB against the original (Pillow: 24.7 dB)
jpeg greyscale613PSNR 36.5 dB against the original (Pillow: 36.5 dB)
jpeg progressive917refused: Only baseline sequential Huffman JPEG is supported.
zlib level 06011identical
zlib level 11670identical
zlib level 61645identical
zlib level 91645identical

Files written by this library, read by Python’s:

Table 26.8. Image files written by the library and read by Python.

file written by the library (read by)result
PNG, L, 8-bit (Pillow)read as L, identical: True
PNG, LA, 8-bit (Pillow)read as LA, identical: True
PNG, RGB, 8-bit (Pillow)read as RGB, identical: True
PNG, RGBA, 8-bit (Pillow)read as RGBA, identical: True
PNG, greyscale, 16-bit (Pillow)read as I;16, identical: True
PGM (Pillow)read as L, identical: True
PPM (Pillow)read as RGB, identical: True
JPEG, greyscale, quality 50 (Pillow)decodes; PSNR 28.0 dB
JPEG, greyscale, quality 90 (Pillow)decodes; PSNR 38.4 dB
JPEG, RGB, quality 50 (Pillow)decodes; PSNR 21.1 dB
JPEG, RGB, quality 90 (Pillow)decodes; PSNR 30.9 dB
zlib stream, level 0 (zlib)decompresses: True; 3181 bytes (zlib’s own: 3181)
zlib stream, level 6 (zlib)decompresses: True; 278 bytes (zlib’s own: 212)
zlib stream, level 9 (zlib)decompresses: True; 278 bytes (zlib’s own: 212)

A decoder must not trust its header. Fuzz testing found no panics in about 36 000 truncated or corrupted files, but a header claiming an enormous image can make a decoder allocate before it checks the data: a 24-byte Netpbm file asked for 320 GB and aborted the process. Each of the three decoders therefore checks the claim against the data first.

Algorithm

Decoding a PNG.

  1. Check the signature. Read the chunks in order, verifying the CRC of each.
  2. Read the dimensions, bit depth, colour type and interlacing from IHDR, and the palette from PLTE if there is one.
  3. Concatenate the contents of all the IDAT chunks and decompress them with inflate.
  4. Check that the decompressed length is what the header implies.
  5. Undo the filter of each row, using the row above and the pixel to the left as the filter type requires. With Adam7 interlacing, do this for each of the seven passes and place the pixels in their positions.
  6. Unpack samples of fewer than eight bits, scale them to eight, and replace palette indices by their colours.

Encoding a PNG.

  1. For each row, apply each of the five filters and keep the one whose output has the smallest sum of absolute values; prefix the row with the filter’s number.
  2. Compress the filtered rows as a zlib stream.
  3. Write the signature and the IHDR, IDAT and IEND chunks, each with its CRC.

Encoding a JPEG.

  1. Convert each pixel from RGB to .
  2. For each block of each component: subtract 128, take the two-dimensional DCT, divide each coefficient by its quantisation table entry, and round.
  3. Reorder the 64 coefficients in zig-zag order.
  4. Code the DC coefficient as its difference from the previous block’s, and the AC coefficients as pairs (run of zeros, value), ending with an end-of-block symbol.
  5. Write the Huffman codes of these symbols. Whenever a byte of the output is 0xFF, write a zero byte after it (byte stuffing), so that it is not mistaken for a marker.

Decoding a JPEG.

  1. Parse the marker segments: quantisation tables, the frame header (dimensions, components and sampling factors), Huffman tables, the restart interval and the scan header.
  2. Check that the components in the scan match the frame.
  3. For each minimum coded unit (the group of blocks covering one sampling period), Huffman-decode the coefficients of each block, undoing the DC prediction and the zig-zag order.
  4. Multiply by the quantisation table and take the inverse DCT; add 128.
  5. Upsample the chroma components to full resolution.
  6. Convert to RGB and clamp to the range of a byte.

Implementation

  • RasterImage holds interleaved u16 samples with 1 to 4 channels at 8 or 16 bits, shared by PNG and Netpbm; JpegImage holds 8-bit greyscale or RGB.
  • png_encode takes a zlib level 0 to 9; jpeg_encode a quality 1 to 100.

In practice

//! PNG, JPEG and Netpbm images.

use lib_jsl_file_io::{RasterImage, jpeg_decode, jpeg_encode, png_decode, png_encode, ppm_decode, ppm_encode, read_png_file, write_png_file};

fn main() {
    // A 64 x 48 RGB test card: colour ramps and a diagonal stripe.
    let (w, h) = (64, 48);
    let samples: Vec<u16> = (0..h)
        .flat_map(|y| (0..w).flat_map(move |x| [(x * 4) as u16, (y * 5) as u16, if (x + y) % 16 < 8 { 220 } else { 30 }]))
        .collect();
    let image = RasterImage::new(w, h, 3, 8, samples.clone()).unwrap();

    let png = png_encode(&image, 9).unwrap();
    println!("PNG: {} bytes for {} raw, decodes identically: {}", png.len(), w * h * 3, png_decode(&png).unwrap() == image);
    let path = std::env::temp_dir().join("lib_jsl_card.png");
    write_png_file(&path, &image).unwrap();
    println!("PNG file round trip identical: {}", read_png_file(&path).unwrap() == image);

    let ppm = ppm_encode(&image).unwrap();
    println!("PPM: {} bytes, header {:?}, identical: {}", ppm.len(), String::from_utf8_lossy(&ppm[..13]), ppm_decode(&ppm).unwrap() == image);

    let bytes: Vec<u8> = samples.iter().map(|&v| v as u8).collect();
    for quality in [25, 75, 95] {
        let jpeg = jpeg_encode(&bytes, w, h, 3, quality).unwrap();
        let back = jpeg_decode(&jpeg).unwrap();
        let mse = bytes.iter().zip(&back.pixels).map(|(&a, &b)| (a as f64 - b as f64).powi(2)).sum::<f64>() / bytes.len() as f64;
        println!("JPEG quality {quality}: {} bytes, PSNR {:.1} dB", jpeg.len(), 10.0 * (255.0f64.powi(2) / mse).log10());
    }
}
PNG: 269 bytes for 9216 raw, decodes identically: true
PNG file round trip identical: true
PPM: 9229 bytes, header "P6\n64 48\n255\n", identical: true
JPEG quality 25: 1113 bytes, PSNR 20.6 dB
JPEG quality 75: 2091 bytes, PSNR 28.9 dB
JPEG quality 95: 4404 bytes, PSNR 39.2 dB

The test card’s ramps and stripes are almost perfectly predictable after filtering, so PNG stores 9216 bytes of pixels in 269.

Strengths

  • Complete PNG decoding, Netpbm in all six forms, and baseline JPEG equal to libjpeg’s at the same quality, including the upsampling of subsampled files.
  • Robust decoders: no panics on damaged files, and no huge allocations from forged headers.

Weaknesses

  • The DEFLATE encoder uses only the fixed Huffman code and greedy matching, so PNG files are 5–10% larger than zlib’s.
  • No progressive JPEG, no chroma subsampling when encoding, and no metadata (EXIF, colour profiles, text chunks) beyond what decoding needs.

Exercises

  1. Show that the Paeth predictor gives exact predictions on a linear ramp in either direction.
  2. Explain why PNG filters work on bytes rather than on pixel values, and what bpp means for 16-bit or sub-byte images.
  3. Show that the 8×8 DCT is orthogonal, and that quantisation error in the coefficients equals the pixel error in the mean-square sense.
  4. Show that the IJG quality scaling halves the table entries going from quality 50 to 75.
  5. Design a DEFLATE input on which lazy matching beats greedy matching.
Hints and answers
  1. Paeth chooses among left , above and upper-left the neighbour closest to . On a ramp that depends only on , so exactly; on a vertical ramp so ; in both cases the chosen neighbour predicts the pixel exactly.
  2. Filters operate on bytes so that the same code works at every bit depth; bpp is the number of bytes per complete pixel (rounded up to at least 1 for sub-byte images), the distance to the corresponding byte of the left neighbour.
  3. The 8×8 DCT is a separable orthogonal transform, so by Parseval the sum of squared coefficient errors equals the sum of squared pixel errors.
  4. IJG scale factor: for (as a percentage), i.e. 100% at and 50% at : the table entries halve.
  5. Lazy matching helps when a match found at position is shorter than the one starting at : for example, with earlier text abc bcdef and later abcdef, greedy takes abc then def as literals or short matches, while lazy takes literal a and the longer match bcdef.

Further reading

  • Portable Network Graphics (PNG) Specification, 3rd ed., W3C Recommendation, 2025; and RFC 1950–1951 for zlib and DEFLATE.
  • G. K. Wallace, “The JPEG still picture compression standard”, Communications of the ACM 34 (1991) 30–44.
  • W. B. Pennebaker and J. L. Mitchell, JPEG: Still Image Data Compression Standard, Van Nostrand Reinhold, 1993.
  • N. Ahmed, T. Natarajan and K. R. Rao, “Discrete cosine transform”, IEEE Transactions on Computers C-23 (1974) 90–93.