Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

PNG Row Filter Desk: Why a Smaller Row Score Can Produce a Larger File

PNG can preserve the same RGBA8 bytes in several different forms. The step worth inspecting happens before compression: each row is filtered by predicting a byte from earlier bytes and storing a reversible difference. PN

PNG Row Filter Desk: Why a Smaller Row Score Can Produce a Larger File

PNG can preserve the same RGBA8 bytes in several different forms. The step worth inspecting happens before compression: each row is filtered by predicting a byte from earlier bytes and storing a reversible difference. PNG Row Filter Desk exposes that step for small numeric grids, then hands the filtered stream to the platform DEFLATE encoder and assembles a downloadable PNG. The row score used to pick a filter is a useful local signal; it does not measure final file size.

The input is a plain {width,height,rgba} object. Width and height are integers from 1 to 32. The flat rgba array is row-major and holds exactly four byte values per pixel, R, G, B, and A, with no inferred premultiplication. A preview can display those bytes, but it is not a byte-equality check. Fully transparent pixels still carry RGB bytes. The one-pixel sample [17,201,129,0] looks empty in many composited previews, yet the decoded stream still contains 17, 201, and 129.

One fixed commit contains the reference implementation and the original examples: reference.py, core.mjs, and the contract. The public tools are the Hugging Face Space and the live static app. Filter functions and tie rules follow the W3C PNG Third Edition. The implementation, synthetic grids, and fixtures are mine under Apache-2.0, with attribution in NOTICE.

The filtering arithmetic

For each byte x in row y, the left neighbor a is four bytes earlier in the same row because RGBA has four bytes per pixel. The up neighbor b is the same position in the previous row. The upper-left neighbor c is four bytes earlier in the previous row. A missing neighbor is zero. The predictors are None = 0, Sub = a, Up = b, Average = floor((a+b)/2), and Paeth. Paeth chooses whichever of a, b, c is closest to a+b-c; ties choose a first, then b, then c. The filtered byte is f = (x - predictor) mod 256. Its signed form is f when f is below 128 and f - 256 otherwise. The row score is the sum of absolute signed residuals.

Reconstruction uses the already decoded previous bytes, so it mirrors what a decoder can do. It never uses the original raw neighbors after filtering. The filter-type byte is prepended to each row after scoring, which means it changes the scanline but does not change the already computed row score.

From rows to compressed IDAT

Each row contributes one type byte and one filtered byte per RGBA byte. The total scanline length is height * (4 * width + 1). Each strategy produces one scanline stream. The browser compresses each complete stream once through CompressionStream('deflate'), zlib-wrapped DEFLATE. The implementation does not compress each row separately and does not write its own DEFLATE encoder. For some inputs two strategies can produce the same scanline; the encoder does not assume the six streams are distinct.

A PNG in this profile consists of the eight-byte signature, IHDR, one IDAT, and IEND. Every chunk CRC covers its type and data. The total is 57 + compressed_IDAT_bytes. The 57 is a fixed structural overhead count: signature 8, IHDR 25, IDAT 12 including its four-byte length field, IEND 12. That count stays fixed, but it does not mean those structure bytes have identical values across strategies. The IDAT length field changes when the compressed payload length changes.

Why a lower row score can still produce a larger file

The white 4×3 example makes the mechanism visible. Its source is forty-eight bytes of 255. With None, every prediction is 0, so every filtered byte is 255. Each signed residual is -1, each row scores 16, and the total is 48. The heuristic picks Sub for the first row. The first pixel has no left neighbor, so its four bytes each produce residual 255 and contribute four signed points together; the other twelve bytes of that row score zero. The next two rows pick Up because they match the row above, so all their residuals are zero. The heuristic total is 4, much lower than None.

The streams actually passed to DEFLATE differ. None begins with type byte 0 and then a long run of 255; heuristic begins with type byte 1, then ff ff ff ff, then mostly zeros. The measured browser output was 78 bytes for heuristic and 72 bytes for None. The local Python check described later gives 77 and 72 with the fixed 57-byte structure and zlib.compress. Both measurements point the same way, yet the absolute browser and local numbers differ by one byte in this case. I have not done an internal analysis of what causes that one-byte difference. After filtering, each strategy reconstructs the same RGBA through its own unfilter pass. None and heuristic do not share one identical filtered scanline, and verify_png compares each strategy against its own expected scanline rather than a common one.

The vertical-ramp case is another fixed input. Its name describes the sample set, not an inferred gradient axis. The 8×4 grid repeats the same row: each pixel has RGB values 31 * x for x from 0 to 7 and alpha 255. Fixed Sub uses the left neighbor in every row, so its filtered pattern repeats across rows, and its row score is 2608. The heuristic chooses Sub for the first row and Up for the later rows, total 652. The browser measured 82 bytes for heuristic and 79 bytes for fixed Sub. The local fixed-structure check also produces 82 and 79. Compression can use that overall row repetition. What the measured sizes show is that a smaller row score did not produce a smaller file here. I have not analyzed the platform's DEFLATE tokens or run a controlled comparison of these two streams, so I do not attribute the specific byte difference to a particular internal cause.

Input Heuristic score Fixed score Browser PNG bytes Local fixed 57 + zlib
white 4×3 4 None 48 heuristic 78, None 72 heuristic 77, None 72
vertical-ramp 8×4 652 Sub 2608 heuristic 82, Sub 79 heuristic 82, Sub 79

Local values are a length cross-check computed with Python stdlib zlib and the fixed 57-byte structure. They are not a reproduction of the browser's CompressionStream bytes. Where the ramp lengths match, that says nothing about whether the underlying stream bytes match. Both inputs were fixed before the compression measurements; they are observable counterexamples from one environment, not a population frequency or a universal ranking.

What to keep when investigating an unexpected size

The most useful preserved values are the five row scores per row, the selected score and filter type, the per-byte predictor/residual/reconstructed values, the complete type-prefixed scanline hex, the actual compressed IDAT hex and length, and the PNG chunk offsets with CRC equality. A score total alone does not explain a large file. When a small score produces a large output, compare the selected row types and the actual compressed IDAT, then confirm that decompressing the IDAT returns exactly that strategy's scanline and that unfiltering it returns the source RGBA. For a downloaded PNG, CRC checks the type and data fields of each chunk. Confirming the file as a whole takes more checks: signature, IHDR fields, IHDR/IDAT/IEND order, CRC, zlib decompression reaching EOF with no leftover tail, scanline equality, and independent unfilter. CRC alone does not prove structural integrity, security, or full PNG conformance.

For a local sanity check, the following script downloads the fixed reference.py and examples.json, then uses only filtered(request) and local zlib.compress. It prints filtering results and a local 57 + compressed length figure. It does not build a new PNG, verify CRC, or claim to reproduce the browser's CompressionStream bytes.

#!/usr/bin/env sh
set -eu
d="png-desk-check"
mkdir -p "$d" && cd "$d"
base="https://huggingface.co/spaces/WideChaos/png-row-filter-desk/raw/d91afff4dcdce24eb5e8f3b2d247bb8aa098ebf0"
curl -fsSLO "$base/reference.py"
curl -fsSLO "$base/examples.json"
python3 - <<'PY'
import importlib.util, json, zlib
spec = importlib.util.spec_from_file_location("ref", "reference.py")
ref = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ref)
examples = json.load(open("examples.json"))
for name in ("white", "vertical-ramp"):
    req = next(e["request"] for e in examples if e["id"] == name)
    print(f"{name} {req['width']}x{req['height']}")
    for s in ref.filtered(req)["strategies"]:
        scan = bytes.fromhex(s["scanline_hex"])
        print(s["strategy"], "score", s["score_total"], "scanline", len(scan),
              "local_57_plus_zlib", 57 + len(zlib.compress(scan)),
              "roundtrip", s["exact_rgba_roundtrip"])
PY

verify_png(blob, request, scanline) is the matching entry for checking a real PNG downloaded from a report. It verifies the signature, IHDR fields, IHDR/IDAT/IEND order, chunk CRC, decompression to the end of the zlib stream with no leftover tail, exact equality with the supplied scanline for that strategy, and an independent unfilter pass back to the supplied RGBA. That combination is stronger than a visual preview or a row score.

The original screenshot below shows the default 16×12 source and decoded preview along with the six measured PNG sizes. Clicking opens the original.

Original default 16×12 result page with the source preview, decoded preview, and six measured PNG sizes.

The five predictors, CRC32, and chunk layout are standard PNG mechanics. The heuristic is a declared row-choice rule in this desk, not a rule the specification requires. Six strategies are six lossless encodings of one grid, so equal or different sizes are observations about those encodings, not evidence that any predictor is universally better.

English original: PNG Row Filter Desk: Why a Smaller Row Score Can Produce a Larger File.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.