Spielerando

PNG pixels

Reads a PNG file into its real pixels and writes pixels back as a PNG file, with nothing to install. It tells you how big the picture really is and whether its background is truly see-through or only painted to look that way.

Two pictures of the beekeeper sit side by side in an image viewer, both on the same grey and white checkerboard, and look exactly alike. Both slide down into a sunny meadow. The left one arrives alone and the sky shows around her; the right one brings a checkered box with it. Next to them, tags show the see-through pixels the reader counted: a number with a green lamp on the left, 0 with a red lamp on the right.
Two files that look the same in an image viewer. The reader counts the see-through pixels in each: 0 in the right one, because its checkerboard was painted into the picture and comes along into the game. The left one really has them, 267 pixels, so only the beekeeper arrives.
Two beetles side by side, big enough to see every pixel. In daylight they look almost the same. Then night falls over the scene: around the left beetle a pale, speckled rim lights up, the partly see-through pixels; the right beetle has a clean dark edge. Tags show how many partly see-through pixels the reader counted: a number with a red lamp on the left, 0 with a green lamp on the right. Then day comes back.
Soft edges hide on a light background and glow on a dark one. The reader counts them from the file instead of the looks: 35 partly see-through pixels around the left beetle, the pale rim an image tool left, and 0 around the right one, which is what pixel art should have.

When you need it

Whenever your AI should measure a picture instead of describing how it looks: before a sprite from an image tool goes into your game, and to save a sprite your AI made as a file. A file that is named PNG and is really a JPEG, WebP or GIF is called what it is. It reads every standard PNG, checks the file's checksums, and stops with a plain message when the file is damaged.

Say this to your AI

Use the PNG pixels recipe from Spielerando to open my picture file. Tell me its real width and height, how many pixels are fully see-through and how many are partly see-through, from the numbers in the file and not from how it looks.

The button copies this text together with the tested code below, so your AI has everything.

Settings

The code

Tested TypeScript with no outside parts. Copy it into your game, or hand it to your AI together with the text above.

/* PNG pixels: reads a PNG file into its real pixels and writes pixels as a PNG file, with nothing
   to install. It is for measuring a picture instead of looking at it: how big it really is, and
   whether its background is truly see-through or only painted to look that way.

   Usage:
     const picture = readPng(bytes);        // bytes: a Uint8Array, from a file or a download
     picture.width; picture.height;
     picture.data;                          // four numbers a pixel: red, green, blue, opacity
     picture.transparentPixels;             // how many pixels are fully see-through
     picture.softPixels;                    // how many are partly see-through
     picture.hasAlpha;                      // false: this file cannot hold a see-through pixel

     const file = writePng(picture);        // a Uint8Array to save as "name.png"

   In Node:     readPng(fs.readFileSync("squire.png"))
   In a browser: readPng(new Uint8Array(await file.arrayBuffer()))
   The pixels have the shape a canvas uses, so `new ImageData(picture.data, picture.width)` shows them.

   What it reads: every standard PNG, which means grey, colour and palette pictures, with 1 to 16
   bits a channel, with or without opacity, plain or interlaced. Sixteen-bit channels are cut to
   eight. It checks the file's checksums and stops with a message that says what is wrong.

   What it does not read: JPEG, WebP and GIF. A file ending in .png that is one of those is named
   for what it is, because a JPEG cannot hold a see-through pixel at all.

   What it writes: a plain, correct PNG with eight bits a channel and no compression, so a 32 by 32
   sprite takes about 4 KB. Any image tool makes it smaller later without changing a pixel.

   SPDX-License-Identifier: MIT
   Copyright (c) 2026 Spielerando, https://spielerando.com */

export const DEFAULTS = {
  /** The most pixels a picture may have before reading is refused: this is 4096 by 4096. */
  maxPixels: 16777216,
};

export type PngSettings = Partial<typeof DEFAULTS>;

/** A picture as a canvas holds it: four numbers a pixel (red, green, blue, opacity), row by row. */
export interface Pixels {
  width: number;
  height: number;
  data: Uint8ClampedArray;
}

export interface Png extends Pixels {
  /** How the file stores a pixel. */
  kind: "grey" | "colour" | "palette" | "grey with opacity" | "colour with opacity";
  /** Bits a channel in the file: 1, 2, 4, 8 or 16. */
  bitDepth: number;
  /** Whether the file can hold see-through pixels at all. */
  hasAlpha: boolean;
  /** Pixels with opacity 0. */
  transparentPixels: number;
  /** Pixels with an opacity between 1 and 254: soft edges. */
  softPixels: number;
}

const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];

let crcTable: Uint32Array | undefined;
function crc32(bytes: Uint8Array, from: number, to: number): number {
  if (!crcTable) {
    crcTable = new Uint32Array(256);
    for (let n = 0; n < 256; n++) {
      let c = n;
      for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
      crcTable[n] = c >>> 0;
    }
  }
  let crc = 0xffffffff;
  for (let i = from; i < to; i++) crc = crcTable[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
  return (crc ^ 0xffffffff) >>> 0;
}

function adler32(bytes: Uint8Array): number {
  let a = 1;
  let b = 0;
  for (let i = 0; i < bytes.length; ) {
    // sums stay below 2^32 for 3800 bytes at a time
    const end = Math.min(i + 3800, bytes.length);
    for (; i < end; i++) {
      a += bytes[i];
      b += a;
    }
    a %= 65521;
    b %= 65521;
  }
  return ((b << 16) | a) >>> 0;
}

const LENGTH_BASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
const LENGTH_EXTRA = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
const DISTANCE_BASE = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
const DISTANCE_EXTRA = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
const CODE_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];

interface Codes {
  count: Uint16Array;
  symbol: Uint16Array;
}

/** The table for one set of codes, from the length of each symbol's code. */
function codesFrom(lengths: number[] | Uint8Array): Codes {
  const count = new Uint16Array(16);
  for (const length of lengths) count[length]++;
  count[0] = 0;
  const offset = new Uint16Array(16);
  for (let i = 1; i < 16; i++) offset[i] = offset[i - 1] + count[i - 1];
  const symbol = new Uint16Array(lengths.length);
  for (let s = 0; s < lengths.length; s++) if (lengths[s] !== 0) symbol[offset[lengths[s]]++] = s;
  return { count, symbol };
}

/** Unpacks the data of a PNG (zlib): `size` is how many bytes the picture's rows need. */
function unpack(src: Uint8Array, size: number): Uint8Array {
  const broken = (what: string) => new Error(`The picture's data is damaged: ${what}.`);
  if (src.length < 6) throw broken("it is too short");
  if ((src[0] & 0x0f) !== 8 || ((src[0] << 8) | src[1]) % 31 !== 0 || src[1] & 0x20) throw broken("it does not start as packed PNG data does");
  const out = new Uint8Array(size);
  let at = 0;
  let pos = 2;
  let hold = 0;
  let held = 0;
  const bits = (n: number) => {
    while (held < n) {
      if (pos >= src.length) throw broken("it ends in the middle");
      hold |= src[pos++] << held;
      held += 8;
    }
    const value = hold & ((1 << n) - 1);
    hold >>>= n;
    held -= n;
    return value;
  };
  const read = (codes: Codes) => {
    let code = 0;
    let first = 0;
    let index = 0;
    for (let length = 1; length < 16; length++) {
      code |= bits(1);
      const count = codes.count[length];
      if (code - count < first) return codes.symbol[index + (code - first)];
      index += count;
      first = (first + count) << 1;
      code <<= 1;
    }
    throw broken("a code in it does not exist");
  };
  const put = (byte: number) => {
    if (at >= size) throw broken("it holds more than the picture's size needs");
    out[at++] = byte;
  };

  let last = false;
  while (!last) {
    last = bits(1) === 1;
    const type = bits(2);
    if (type === 0) {
      hold = 0;
      held = 0;
      if (pos + 4 > src.length) throw broken("it ends in the middle");
      const length = src[pos] | (src[pos + 1] << 8);
      if ((length ^ 0xffff) !== (src[pos + 2] | (src[pos + 3] << 8))) throw broken("a block's length does not match its check");
      pos += 4;
      if (pos + length > src.length) throw broken("it ends in the middle");
      for (let i = 0; i < length; i++) put(src[pos++]);
      continue;
    }
    if (type === 3) throw broken("it has a block of an unknown kind");
    let literals: Codes;
    let distances: Codes;
    if (type === 1) {
      const lengths = new Uint8Array(288);
      lengths.fill(8, 0, 144).fill(9, 144, 256).fill(7, 256, 280).fill(8, 280, 288);
      literals = codesFrom(lengths);
      distances = codesFrom(new Uint8Array(30).fill(5));
    } else {
      const literalCount = bits(5) + 257;
      const distanceCount = bits(5) + 1;
      const codeCount = bits(4) + 4;
      const codeLengths = new Uint8Array(19);
      for (let i = 0; i < codeCount; i++) codeLengths[CODE_ORDER[i]] = bits(3);
      const lengthCodes = codesFrom(codeLengths);
      const lengths = new Uint8Array(literalCount + distanceCount);
      for (let i = 0; i < lengths.length; ) {
        const symbol = read(lengthCodes);
        if (symbol < 16) {
          lengths[i++] = symbol;
          continue;
        }
        let repeat: number;
        let value = 0;
        if (symbol === 16) {
          if (i === 0) throw broken("it repeats a length before giving one");
          value = lengths[i - 1];
          repeat = 3 + bits(2);
        } else repeat = symbol === 17 ? 3 + bits(3) : 11 + bits(7);
        if (i + repeat > lengths.length) throw broken("it lists more code lengths than it announced");
        while (repeat-- > 0) lengths[i++] = value;
      }
      literals = codesFrom(lengths.subarray(0, literalCount));
      distances = codesFrom(lengths.subarray(literalCount));
    }
    for (;;) {
      const symbol = read(literals);
      if (symbol < 256) {
        put(symbol);
        continue;
      }
      if (symbol === 256) break;
      if (symbol > 285) throw broken("it has a length that does not exist");
      const length = LENGTH_BASE[symbol - 257] + bits(LENGTH_EXTRA[symbol - 257]);
      const d = read(distances);
      if (d > 29) throw broken("it has a distance that does not exist");
      const distance = DISTANCE_BASE[d] + bits(DISTANCE_EXTRA[d]);
      if (distance > at) throw broken("it points back before its own start");
      for (let i = 0; i < length; i++) put(out[at - distance]);
    }
  }
  if (at !== size) throw broken(`it holds ${at} bytes and the picture's size needs ${size}`);
  if (pos + 4 > src.length) throw broken("its checksum is missing");
  const sum = ((src[pos] << 24) | (src[pos + 1] << 16) | (src[pos + 2] << 8) | src[pos + 3]) >>> 0;
  if (sum !== adler32(out)) throw broken("its checksum does not match");
  return out;
}

/** Undoes the filter of each row in place. `bpp` is the bytes a whole pixel takes, at least 1. */
function unfilter(rows: Uint8Array, start: number, rowBytes: number, height: number, bpp: number): void {
  for (let y = 0; y < height; y++) {
    const at = start + y * (rowBytes + 1);
    const filter = rows[at];
    if (filter > 4) throw new Error(`The picture's data is damaged: row ${y + 1} names a filter that does not exist.`);
    for (let i = 0; i < rowBytes; i++) {
      const x = at + 1 + i;
      const left = i >= bpp ? rows[x - bpp] : 0;
      const up = y > 0 ? rows[x - rowBytes - 1] : 0;
      const upLeft = y > 0 && i >= bpp ? rows[x - rowBytes - 1 - bpp] : 0;
      let predicted = 0;
      if (filter === 1) predicted = left;
      else if (filter === 2) predicted = up;
      else if (filter === 3) predicted = (left + up) >> 1;
      else if (filter === 4) {
        const p = left + up - upLeft;
        const pa = Math.abs(p - left);
        const pb = Math.abs(p - up);
        const pc = Math.abs(p - upLeft);
        predicted = pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft;
      }
      rows[x] = (rows[x] + predicted) & 0xff;
    }
  }
}

const KINDS: Record<number, [Png["kind"], number]> = { 0: ["grey", 1], 2: ["colour", 3], 3: ["palette", 1], 4: ["grey with opacity", 2], 6: ["colour with opacity", 4] };
const DEPTHS: Record<number, number[]> = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
/** The seven passes of an interlaced picture: where each starts and how far its pixels are apart. */
const PASSES = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];

/** Reads a PNG file into its pixels, or stops with a message that says what is wrong with the file. */
export function readPng(bytes: Uint8Array, settings: PngSettings = {}): Png {
  const { maxPixels = DEFAULTS.maxPixels } = settings;
  const starts = (...values: number[]) => values.every((v, i) => bytes[i] === v);
  if (!SIGNATURE.every((v, i) => bytes[i] === v)) {
    if (starts(0xff, 0xd8)) throw new Error("This is a JPEG file, whatever its name says. A JPEG cannot hold see-through pixels; ask for a PNG.");
    if (starts(0x52, 0x49, 0x46, 0x46) && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) throw new Error("This is a WebP file, whatever its name says. Save it as a PNG first.");
    if (starts(0x47, 0x49, 0x46, 0x38)) throw new Error("This is a GIF file, whatever its name says. Save it as a PNG first.");
    throw new Error("This is not a PNG file: it does not start the way every PNG does.");
  }
  const int = (at: number) => ((bytes[at] << 24) | (bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3]) >>> 0;
  let width = 0;
  let height = 0;
  let bitDepth = 0;
  let colorType = -1;
  let interlaced = false;
  let palette: Uint8Array | undefined;
  let seeThrough: Uint8Array | undefined;
  const packed: Uint8Array[] = [];
  let ended = false;
  for (let at = 8; !ended; ) {
    if (at + 12 > bytes.length) throw new Error("The PNG file is cut off: it ends before its last part.");
    const length = int(at);
    const name = String.fromCharCode(bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]);
    const from = at + 8;
    if (from + length + 4 > bytes.length) throw new Error(`The PNG file is cut off inside its part "${name}".`);
    if (crc32(bytes, at + 4, from + length) !== int(from + length)) throw new Error(`The PNG file is damaged: the checksum of its part "${name}" does not match.`);
    if (colorType < 0 && name !== "IHDR") throw new Error("The PNG file is damaged: it does not begin with its size.");
    if (name === "IHDR") {
      if (length !== 13) throw new Error("The PNG file is damaged: its first part has the wrong length.");
      width = int(from);
      height = int(from + 4);
      bitDepth = bytes[from + 8];
      colorType = bytes[from + 9];
      if (!KINDS[colorType] || !DEPTHS[colorType].includes(bitDepth)) throw new Error(`The PNG file names a kind of picture that does not exist (colour type ${colorType}, ${bitDepth} bits).`);
      if (bytes[from + 10] !== 0 || bytes[from + 11] !== 0 || bytes[from + 12] > 1) throw new Error("The PNG file names a way of packing that does not exist.");
      interlaced = bytes[from + 12] === 1;
      if (width === 0 || height === 0) throw new Error("The PNG file says the picture has no pixels.");
      if (width * height > maxPixels) throw new Error(`The picture is ${width} by ${height} pixels, more than the ${maxPixels} pixels allowed.`);
    } else if (name === "PLTE") palette = bytes.subarray(from, from + length);
    else if (name === "tRNS") seeThrough = bytes.subarray(from, from + length);
    else if (name === "IDAT") packed.push(bytes.subarray(from, from + length));
    else if (name === "IEND") ended = true;
    at = from + length + 4;
  }
  if (packed.length === 0) throw new Error("The PNG file has no picture data.");
  if (colorType === 3 && (!palette || palette.length % 3 !== 0 || palette.length === 0)) throw new Error("The PNG file is a palette picture without a usable palette.");

  const [kind, channels] = KINDS[colorType];
  const bitsPerPixel = channels * bitDepth;
  const bpp = Math.max(1, bitsPerPixel >> 3);
  const rowBytesOf = (w: number) => Math.ceil((w * bitsPerPixel) / 8);
  const passes = interlaced
    ? PASSES.map(([x0, y0, dx, dy]) => ({ x0, y0, dx, dy, w: Math.ceil((width - x0) / dx), h: Math.ceil((height - y0) / dy) })).filter((p) => p.w > 0 && p.h > 0)
    : [{ x0: 0, y0: 0, dx: 1, dy: 1, w: width, h: height }];
  const size = passes.reduce((sum, p) => sum + p.h * (rowBytesOf(p.w) + 1), 0);
  const joined = new Uint8Array(packed.reduce((sum, part) => sum + part.length, 0));
  let offset = 0;
  for (const part of packed) {
    joined.set(part, offset);
    offset += part.length;
  }
  const rows = unpack(joined, size);

  const data = new Uint8ClampedArray(width * height * 4);
  const max = (1 << bitDepth) - 1;
  // a grey or colour picture without opacity may name one colour as see-through
  const keyed = seeThrough && (colorType === 0 || colorType === 2) ? Array.from({ length: channels }, (_, c) => (seeThrough[c * 2] << 8) | seeThrough[c * 2 + 1]) : undefined;
  let start = 0;
  for (const pass of passes) {
    const rowBytes = rowBytesOf(pass.w);
    unfilter(rows, start, rowBytes, pass.h, bpp);
    for (let py = 0; py < pass.h; py++) {
      const row = start + py * (rowBytes + 1) + 1;
      /** One channel's value as the file has it, at its full depth. */
      const sample = (index: number) => {
        if (bitDepth === 8) return rows[row + index];
        if (bitDepth === 16) return (rows[row + index * 2] << 8) | rows[row + index * 2 + 1];
        const bit = index * bitDepth;
        return (rows[row + (bit >> 3)] >> (8 - bitDepth - (bit & 7))) & max;
      };
      const to8 = (v: number) => (bitDepth === 8 ? v : bitDepth === 16 ? v >> 8 : Math.round((v * 255) / max));
      for (let px = 0; px < pass.w; px++) {
        const to = ((pass.y0 + py * pass.dy) * width + pass.x0 + px * pass.dx) * 4;
        const s = px * channels;
        if (colorType === 3) {
          const index = sample(s);
          if (index * 3 + 2 >= palette!.length) throw new Error("The PNG file is damaged: a pixel names a colour its palette does not have.");
          data[to] = palette![index * 3];
          data[to + 1] = palette![index * 3 + 1];
          data[to + 2] = palette![index * 3 + 2];
          data[to + 3] = seeThrough && index < seeThrough.length ? seeThrough[index] : 255;
        } else if (colorType === 0 || colorType === 4) {
          const grey = sample(s);
          data[to] = data[to + 1] = data[to + 2] = to8(grey);
          data[to + 3] = colorType === 4 ? to8(sample(s + 1)) : keyed && keyed[0] === grey ? 0 : 255;
        } else {
          const r = sample(s);
          const g = sample(s + 1);
          const b = sample(s + 2);
          data[to] = to8(r);
          data[to + 1] = to8(g);
          data[to + 2] = to8(b);
          data[to + 3] = colorType === 6 ? to8(sample(s + 3)) : keyed && keyed[0] === r && keyed[1] === g && keyed[2] === b ? 0 : 255;
        }
      }
    }
    start += pass.h * (rowBytes + 1);
  }
  let transparentPixels = 0;
  let softPixels = 0;
  for (let i = 3; i < data.length; i += 4) {
    if (data[i] === 0) transparentPixels++;
    else if (data[i] !== 255) softPixels++;
  }
  return { width, height, data, kind, bitDepth, hasAlpha: colorType === 4 || colorType === 6 || !!seeThrough, transparentPixels, softPixels };
}

/** Writes pixels as a PNG file: eight bits a channel with opacity, not compressed. */
export function writePng(pixels: Pixels): Uint8Array {
  const { width, height, data } = pixels;
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new Error(`A picture needs a width and a height of at least 1, not ${width} by ${height}.`);
  if (data.length !== width * height * 4) throw new Error(`A picture of ${width} by ${height} pixels needs ${width * height * 4} numbers, and there are ${data.length}.`);
  const rowBytes = width * 4 + 1;
  const raw = new Uint8Array(rowBytes * height);
  for (let y = 0; y < height; y++) raw.set(data.subarray(y * width * 4, (y + 1) * width * 4), y * rowBytes + 1);
  // packed "as it is": blocks of at most 65535 bytes, each with its length and the length's check
  const blocks = Math.ceil(raw.length / 65535);
  const packed = new Uint8Array(2 + raw.length + blocks * 5 + 4);
  packed[0] = 0x78;
  packed[1] = 0x01;
  let at = 2;
  for (let b = 0; b < blocks; b++) {
    const part = raw.subarray(b * 65535, Math.min((b + 1) * 65535, raw.length));
    packed[at++] = b === blocks - 1 ? 1 : 0;
    packed[at++] = part.length & 0xff;
    packed[at++] = part.length >> 8;
    packed[at++] = ~part.length & 0xff;
    packed[at++] = (~part.length >> 8) & 0xff;
    packed.set(part, at);
    at += part.length;
  }
  const sum = adler32(raw);
  packed.set([sum >>> 24, (sum >>> 16) & 0xff, (sum >>> 8) & 0xff, sum & 0xff], at);

  const header = new Uint8Array(13);
  header.set([width >>> 24, (width >>> 16) & 0xff, (width >>> 8) & 0xff, width & 0xff, height >>> 24, (height >>> 16) & 0xff, (height >>> 8) & 0xff, height & 0xff, 8, 6, 0, 0, 0]);
  const parts: [string, Uint8Array][] = [["IHDR", header], ["IDAT", packed], ["IEND", new Uint8Array(0)]];
  const file = new Uint8Array(8 + parts.reduce((total, [, body]) => total + 12 + body.length, 0));
  file.set(SIGNATURE);
  let pos = 8;
  for (const [name, body] of parts) {
    file.set([body.length >>> 24, (body.length >>> 16) & 0xff, (body.length >>> 8) & 0xff, body.length & 0xff], pos);
    for (let i = 0; i < 4; i++) file[pos + 4 + i] = name.charCodeAt(i);
    file.set(body, pos + 8);
    const crc = crc32(file, pos + 4, pos + 8 + body.length);
    file.set([crc >>> 24, (crc >>> 16) & 0xff, (crc >>> 8) & 0xff, crc & 0xff], pos + 8 + body.length);
    pos += 12 + body.length;
  }
  return file;
}
The tests this code passes
import assert from "node:assert/strict";
import test from "node:test";
import zlib from "node:zlib";
import { DEFAULTS, type Pixels, readPng, writePng } from "./code.ts";

/* The reader is checked against files packed by Node's own zlib, with every filter, every kind of
   picture and every way of packing; the writer is checked by unpacking its files with zlib. The
   test builds its files itself, so nothing here depends on a picture lying around. */

/** The same numbers on every run. */
function random(seed: number) {
  let s = seed >>> 0;
  return () => {
    s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
    return s / 4294967296;
  };
}

const be = (n: number) => [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255];
function chunk(name: string, body: Uint8Array | number[]): number[] {
  const typed = [...Buffer.from(name, "latin1"), ...body];
  return [...be(body.length), ...typed, ...be(zlib.crc32(Buffer.from(typed)))];
}

const CHANNELS: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };

interface Spec {
  width: number;
  height: number;
  bitDepth: number;
  colorType: number;
  /** One value per channel and pixel, at the file's depth. */
  samples: number[];
  filter?: number | "mixed";
  interlaced?: boolean;
  palette?: number[];
  trns?: number[];
  deflate?: zlib.ZlibOptions;
  /** Cut the packed data into this many IDAT parts. */
  parts?: number;
}

/** The bytes of the rows of one image (or one pass of an interlaced one), filtered. */
function rowsOf(spec: Spec, width: number, height: number, sampleAt: (x: number, y: number, c: number) => number): number[] {
  const channels = CHANNELS[spec.colorType];
  const bitsPerPixel = channels * spec.bitDepth;
  const rowBytes = Math.ceil((width * bitsPerPixel) / 8);
  const bpp = Math.max(1, bitsPerPixel >> 3);
  const plain: number[][] = [];
  for (let y = 0; y < height; y++) {
    const row = new Array<number>(rowBytes).fill(0);
    for (let x = 0; x < width; x++) {
      for (let c = 0; c < channels; c++) {
        const v = sampleAt(x, y, c);
        const index = x * channels + c;
        if (spec.bitDepth === 8) row[index] = v;
        else if (spec.bitDepth === 16) {
          row[index * 2] = v >> 8;
          row[index * 2 + 1] = v & 255;
        } else {
          const bit = index * spec.bitDepth;
          row[bit >> 3] |= v << (8 - spec.bitDepth - (bit & 7));
        }
      }
    }
    plain.push(row);
  }
  const out: number[] = [];
  plain.forEach((row, y) => {
    const filter = spec.filter === "mixed" ? y % 5 : (spec.filter ?? 0);
    out.push(filter);
    for (let i = 0; i < rowBytes; i++) {
      const a = i >= bpp ? row[i - bpp] : 0;
      const b = y > 0 ? plain[y - 1][i] : 0;
      const c = y > 0 && i >= bpp ? plain[y - 1][i - bpp] : 0;
      const p = a + b - c;
      const paeth = Math.abs(p - a) <= Math.abs(p - b) && Math.abs(p - a) <= Math.abs(p - c) ? a : Math.abs(p - b) <= Math.abs(p - c) ? b : c;
      const predicted = [0, a, b, (a + b) >> 1, paeth][filter];
      out.push((row[i] - predicted) & 255);
    }
  });
  return out;
}

const ADAM7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];

function encode(spec: Spec): Uint8Array {
  const channels = CHANNELS[spec.colorType];
  const at = (x: number, y: number, c: number) => spec.samples[(y * spec.width + x) * channels + c];
  let raw: number[] = [];
  if (spec.interlaced) {
    for (const [x0, y0, dx, dy] of ADAM7) {
      const w = Math.ceil((spec.width - x0) / dx);
      const h = Math.ceil((spec.height - y0) / dy);
      if (w > 0 && h > 0) raw = raw.concat(rowsOf(spec, w, h, (x, y, c) => at(x0 + x * dx, y0 + y * dy, c)));
    }
  } else raw = rowsOf(spec, spec.width, spec.height, at);
  const packed = zlib.deflateSync(Buffer.from(raw), spec.deflate ?? {});
  const parts = spec.parts ?? 1;
  const size = Math.ceil(packed.length / parts);
  return new Uint8Array([
    137, 80, 78, 71, 13, 10, 26, 10,
    ...chunk("IHDR", [...be(spec.width), ...be(spec.height), spec.bitDepth, spec.colorType, 0, 0, spec.interlaced ? 1 : 0]),
    ...chunk("tEXt", [...Buffer.from("Software\0a test", "latin1")]),
    ...(spec.palette ? chunk("PLTE", spec.palette) : []),
    ...(spec.trns ? chunk("tRNS", spec.trns) : []),
    ...Array.from({ length: parts }, (_, i) => chunk("IDAT", packed.subarray(i * size, (i + 1) * size))).flat(),
    ...chunk("IEND", []),
  ]);
}

/** What the pixels must be, worked out here from the samples, apart from the reader. */
function expected(spec: Spec): number[] {
  const channels = CHANNELS[spec.colorType];
  const max = (1 << spec.bitDepth) - 1;
  const to8 = (v: number) => (spec.bitDepth === 16 ? v >> 8 : Math.round((v * 255) / max));
  const key = spec.trns && spec.colorType !== 3 ? Array.from({ length: channels }, (_, c) => (spec.trns![c * 2] << 8) | spec.trns![c * 2 + 1]) : null;
  const out: number[] = [];
  for (let i = 0; i < spec.width * spec.height; i++) {
    const s = spec.samples.slice(i * channels, (i + 1) * channels);
    if (spec.colorType === 3) out.push(...spec.palette!.slice(s[0] * 3, s[0] * 3 + 3), spec.trns && s[0] < spec.trns.length ? spec.trns[s[0]] : 255);
    else if (spec.colorType === 0) out.push(to8(s[0]), to8(s[0]), to8(s[0]), key && key[0] === s[0] ? 0 : 255);
    else if (spec.colorType === 4) out.push(to8(s[0]), to8(s[0]), to8(s[0]), to8(s[1]));
    else if (spec.colorType === 2) out.push(to8(s[0]), to8(s[1]), to8(s[2]), key && key.every((k, c) => k === s[c]) ? 0 : 255);
    else out.push(to8(s[0]), to8(s[1]), to8(s[2]), to8(s[3]));
  }
  return out;
}

function make(width: number, height: number, bitDepth: number, colorType: number, seed: number, more: Partial<Spec> = {}): Spec {
  const next = random(seed);
  const channels = CHANNELS[colorType];
  const top = colorType === 3 ? (more.palette?.length ?? 0) / 3 : 1 << bitDepth;
  // smooth runs and noise mixed, so that the packer uses back references and literal bytes alike
  const samples = Array.from({ length: width * height * channels }, (_, i) => (next() < 0.5 ? Math.floor(next() * top) : Math.floor((i / channels) / 7) % top));
  return { width, height, bitDepth, colorType, samples, ...more };
}

const PALETTE = [0x1f, 0x21, 0x42, 0xf2, 0xc1, 0x4e, 0xff, 0xff, 0xff, 0x2f, 0x62, 0xf0];

test("every kind of PNG picture is read to the right pixels, at every depth", () => {
  const kinds: [number, number[], string][] = [[0, [1, 2, 4, 8, 16], "grey"], [2, [8, 16], "colour"], [3, [2, 4, 8], "palette"], [4, [8, 16], "grey with opacity"], [6, [8, 16], "colour with opacity"]];
  let seed = 1;
  for (const [colorType, depths, kind] of kinds) {
    for (const bitDepth of depths) {
      for (const [width, height] of [[1, 1], [7, 5], [33, 9]]) {
        const spec = make(width, height, bitDepth, colorType, seed++, colorType === 3 ? { palette: PALETTE } : {});
        const png = readPng(encode(spec));
        const where = `${kind}, ${bitDepth} bits, ${width} by ${height}`;
        assert.equal(png.width, width, where);
        assert.equal(png.height, height, where);
        assert.equal(png.kind, kind);
        assert.equal(png.bitDepth, bitDepth);
        assert.equal(png.hasAlpha, colorType === 4 || colorType === 6, where);
        assert.deepEqual([...png.data], expected(spec), where);
      }
    }
  }
});

test("a palette picture with one bit a pixel is read too", () => {
  const spec = make(19, 4, 1, 3, 77, { palette: PALETTE.slice(0, 6) });
  assert.deepEqual([...readPng(encode(spec)).data], expected(spec));
});

test("all five row filters are undone, alone and mixed in one picture", () => {
  for (const filter of [0, 1, 2, 3, 4, "mixed"] as const) {
    for (const [colorType, bitDepth] of [[6, 8], [2, 8], [6, 16], [0, 4], [4, 8]]) {
      const spec = make(23, 11, bitDepth, colorType, 100 + colorType + bitDepth, { filter });
      assert.deepEqual([...readPng(encode(spec)).data], expected(spec), `filter ${filter}, colour type ${colorType}, ${bitDepth} bits`);
    }
  }
});

test("every way of packing is unpacked: not packed, fixed codes, codes of its own, and in parts", () => {
  const ways: [string, zlib.ZlibOptions][] = [
    ["not packed", { level: 0 }],
    ["fastest", { level: 1 }],
    ["best", { level: 9 }],
    ["fixed codes", { strategy: zlib.constants.Z_FIXED }],
    ["codes only", { strategy: zlib.constants.Z_HUFFMAN_ONLY }],
    ["runs", { strategy: zlib.constants.Z_RLE }],
    ["small window", { windowBits: 9, level: 9 }],
  ];
  for (const [name, deflate] of ways) {
    for (const [width, height] of [[3, 2], [64, 64], [300, 200]]) {
      const spec = make(width, height, 8, 6, width * 31 + height, { deflate, filter: "mixed", parts: width > 3 ? 5 : 1 });
      assert.deepEqual([...readPng(encode(spec)).data], expected(spec), `${name}, ${width} by ${height}`);
    }
  }
  // more than 65535 bytes not packed means several blocks
  const big = make(200, 100, 8, 6, 5, { deflate: { level: 0 } });
  assert.deepEqual([...readPng(encode(big)).data], expected(big));
});

test("interlaced pictures are put back in order, down to one pixel", () => {
  for (const [width, height] of [[1, 1], [2, 3], [5, 1], [1, 5], [8, 8], [9, 10], [33, 17]]) {
    for (const [colorType, bitDepth] of [[6, 8], [0, 1], [3, 4], [2, 16]]) {
      const spec = make(width, height, bitDepth, colorType, width * 100 + height, { interlaced: true, filter: "mixed", ...(colorType === 3 ? { palette: PALETTE } : {}) });
      assert.deepEqual([...readPng(encode(spec)).data], expected(spec), `${width} by ${height}, colour type ${colorType}, ${bitDepth} bits`);
    }
  }
});

test("see-through pixels are counted from the file, not guessed from the looks", () => {
  // a picture with real opacity: 3 pixels clear, 2 soft, 1 solid
  const real: Spec = { width: 3, height: 2, bitDepth: 8, colorType: 6, samples: [9, 9, 9, 0, 9, 9, 9, 0, 9, 9, 9, 0, 9, 9, 9, 1, 9, 9, 9, 254, 9, 9, 9, 255] };
  const a = readPng(encode(real));
  assert.deepEqual([a.hasAlpha, a.transparentPixels, a.softPixels], [true, 3, 2]);
  // a grey and white checkerboard painted in: the file has no opacity at all
  const painted: Spec = { width: 4, height: 4, bitDepth: 8, colorType: 2, samples: Array.from({ length: 16 }, (_, i) => ((i + (i >> 2)) % 2 ? [204, 204, 204] : [255, 255, 255])).flat() };
  const b = readPng(encode(painted));
  assert.deepEqual([b.hasAlpha, b.transparentPixels, b.softPixels], [false, 0, 0]);
  // a palette with see-through entries, and one colour named as see-through
  const pal = make(9, 9, 2, 3, 3, { palette: PALETTE, trns: [0, 128] });
  const c = readPng(encode(pal));
  assert.equal(c.hasAlpha, true);
  assert.equal(c.transparentPixels, pal.samples.filter((s) => s === 0).length);
  assert.equal(c.softPixels, pal.samples.filter((s) => s === 1).length);
  assert.deepEqual([...c.data], expected(pal));
  const keyed = make(8, 8, 8, 2, 4, { trns: [0, 7, 0, 7, 0, 7] });
  keyed.samples.splice(0, 6, 7, 7, 7, 7, 7, 8);
  const d = readPng(encode(keyed));
  assert.deepEqual([d.hasAlpha, d.transparentPixels], [true, 1]);
  assert.deepEqual([...d.data], expected(keyed));
  const greyKey = make(8, 2, 16, 0, 5, { trns: [0x12, 0x34] });
  greyKey.samples[3] = 0x1234;
  greyKey.samples[4] = 0x1235;
  assert.deepEqual([...readPng(encode(greyKey)).data], expected(greyKey));
  assert.equal(readPng(encode(greyKey)).transparentPixels, 1);
});

test("writing and reading back gives the same pixels", () => {
  const next = random(9);
  for (const [width, height] of [[1, 1], [16, 16], [32, 32], [200, 90]]) {
    const pixels: Pixels = { width, height, data: new Uint8ClampedArray(width * height * 4).map(() => Math.floor(next() * 256)) };
    const png = readPng(writePng(pixels));
    assert.deepEqual([png.width, png.height, png.kind, png.bitDepth], [width, height, "colour with opacity", 8]);
    assert.deepEqual(png.data, pixels.data);
  }
});

test("a written file is a correct PNG: zlib unpacks it and every checksum matches", () => {
  const next = random(10);
  const pixels: Pixels = { width: 150, height: 120, data: new Uint8ClampedArray(150 * 120 * 4).map(() => Math.floor(next() * 256)) };
  const file = Buffer.from(writePng(pixels));
  assert.deepEqual([...file.subarray(0, 8)], [137, 80, 78, 71, 13, 10, 26, 10]);
  const parts: { name: string; body: Buffer }[] = [];
  for (let at = 8; at < file.length; ) {
    const length = file.readUInt32BE(at);
    const body = file.subarray(at + 8, at + 8 + length);
    assert.equal(file.readUInt32BE(at + 8 + length), zlib.crc32(file.subarray(at + 4, at + 8 + length)), "checksum of a part");
    parts.push({ name: file.toString("latin1", at + 4, at + 8), body });
    at += 12 + length;
  }
  assert.deepEqual(parts.map((p) => p.name), ["IHDR", "IDAT", "IEND"]);
  assert.deepEqual([...parts[0].body], [0, 0, 0, 150, 0, 0, 0, 120, 8, 6, 0, 0, 0]);
  // zlib checks the data's own checksum while unpacking
  const rows = zlib.inflateSync(parts[1].body);
  assert.equal(rows.length, 120 * (150 * 4 + 1));
  for (let y = 0; y < 120; y++) {
    assert.equal(rows[y * 601], 0, "each row says it is not filtered");
    assert.deepEqual([...rows.subarray(y * 601 + 1, (y + 1) * 601)], [...pixels.data.subarray(y * 600, (y + 1) * 600)]);
  }
  // a 32 by 32 sprite takes about 4 KB
  assert.equal(writePng({ width: 32, height: 32, data: new Uint8ClampedArray(32 * 32 * 4) }).length, 4196);
});

test("a file that is not a PNG is named for what it is", () => {
  assert.throws(() => readPng(new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 16, 74, 70, 73, 70])), /JPEG file, whatever its name says/);
  assert.throws(() => readPng(new Uint8Array([...Buffer.from("RIFF\x24\0\0\0WEBPVP8 ", "latin1")])), /WebP file/);
  assert.throws(() => readPng(new Uint8Array([...Buffer.from("GIF89a", "latin1")])), /GIF file/);
  assert.throws(() => readPng(new Uint8Array([1, 2, 3])), /not a PNG file/);
  assert.throws(() => readPng(new Uint8Array(0)), /not a PNG file/);
});

test("a damaged or cut-off file stops the reading with what is wrong", () => {
  const spec = make(20, 20, 8, 6, 42);
  const good = encode(spec);
  assert.doesNotThrow(() => readPng(good));
  // every way of cutting the file short is noticed
  for (let length = 8; length < good.length; length += 7) assert.throws(() => readPng(good.subarray(0, length)), /cut off|not a PNG/, `cut to ${length}`);
  // a changed byte inside a part breaks that part's checksum
  for (const at of [20, 80, good.length - 30]) {
    const bad = good.slice();
    bad[at] ^= 0x10;
    assert.throws(() => readPng(bad), /checksum of its part "(IHDR|IDAT)" does not match/, `byte ${at}`);
  }
  // a changed length makes a part reach past the end of the file
  const stretched = good.slice();
  stretched[60] ^= 0x10;
  assert.throws(() => readPng(stretched), /cut off inside its part "IDAT"/);
  // data that is damaged before it was packed into parts, so only its own checksum can tell
  const raw = rowsOf(spec, 20, 20, (x, y, c) => spec.samples[(y * 20 + x) * 4 + c]);
  const packed = zlib.deflateSync(Buffer.from(raw), { level: 0 });
  packed[40] ^= 1;
  const head = [137, 80, 78, 71, 13, 10, 26, 10, ...chunk("IHDR", [...be(20), ...be(20), 8, 6, 0, 0, 0])];
  assert.throws(() => readPng(new Uint8Array([...head, ...chunk("IDAT", packed), ...chunk("IEND", [])])), /checksum does not match/);
  // too little and too much data for the size the file names
  const short = zlib.deflateSync(Buffer.from(raw.slice(0, raw.length - 81)));
  assert.throws(() => readPng(new Uint8Array([...head, ...chunk("IDAT", short), ...chunk("IEND", [])])), /holds 1539 bytes and the picture's size needs 1620/);
  const long = zlib.deflateSync(Buffer.from([...raw, 0]));
  assert.throws(() => readPng(new Uint8Array([...head, ...chunk("IDAT", long), ...chunk("IEND", [])])), /more than the picture's size needs/);
  assert.throws(() => readPng(new Uint8Array([...head, ...chunk("IEND", [])])), /no picture data/);
  assert.throws(() => readPng(new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, ...chunk("IDAT", packed), ...chunk("IEND", [])])), /does not begin with its size/);
});

test("a picture that names what does not exist, or is too big, is refused", () => {
  const head = (body: number[]) => new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, ...chunk("IHDR", body), ...chunk("IDAT", zlib.deflateSync(Buffer.from([0, 0, 0, 0, 0]))), ...chunk("IEND", [])]);
  assert.throws(() => readPng(head([...be(1), ...be(1), 8, 5, 0, 0, 0])), /kind of picture that does not exist/);
  assert.throws(() => readPng(head([...be(1), ...be(1), 4, 6, 0, 0, 0])), /kind of picture that does not exist/);
  assert.throws(() => readPng(head([...be(1), ...be(1), 8, 6, 0, 0, 2])), /way of packing that does not exist/);
  assert.throws(() => readPng(head([...be(0), ...be(1), 8, 6, 0, 0, 0])), /no pixels/);
  assert.equal(DEFAULTS.maxPixels, 4096 * 4096);
  assert.throws(() => readPng(head([...be(4097), ...be(4096), 8, 6, 0, 0, 0])), /4097 by 4096 pixels, more than the 16777216 pixels allowed/);
  assert.throws(() => readPng(encode(make(4, 4, 8, 6, 1)), { maxPixels: 15 }), /more than the 15 pixels allowed/);
  // a palette picture needs its palette, and a pixel cannot name a colour past its end
  assert.throws(() => readPng(encode({ width: 1, height: 1, bitDepth: 8, colorType: 3, samples: [0] })), /without a usable palette/);
  assert.throws(() => readPng(encode({ width: 1, height: 1, bitDepth: 8, colorType: 3, samples: [4], palette: PALETTE })), /a colour its palette does not have/);
});

test("the writer refuses pixels that do not fit their size", () => {
  assert.throws(() => writePng({ width: 2, height: 2, data: new Uint8ClampedArray(15) }), /needs 16 numbers, and there are 15/);
  assert.throws(() => writePng({ width: 0, height: 2, data: new Uint8ClampedArray(0) }), /at least 1/);
  assert.throws(() => writePng({ width: 1.5, height: 2, data: new Uint8ClampedArray(12) }), /at least 1/);
});

Common questions

how do i check if a png is really transparent

Count the pixels whose opacity is zero. A file with no such pixel has a painted background, even if it shows a grey checkerboard, and this recipe gives you that count.

why does my sprite have a checkerboard background in the game

The checkerboard that image programs show for see-through areas was painted into the picture. The file then has no see-through pixel at all, and the fix is to make the picture again with a transparent background, not to rename it.

how do i read a png without a library

A PNG is a short list of parts with checksums, and the pixels are packed in one of them. This recipe unpacks them itself, so it runs in a browser, in Node and anywhere else TypeScript runs, with nothing to install.

Was this page helpful?

One click, no account. It shows us which pages help.

Next step

Code recipe

Pixel art from text

Turns a sprite written as rows of letters into real pixels: one letter is one pixel, and a short list says which letter is which colour. Before it draws anything it reports a row that is too short, a letter with no colour and a frame of another size, each with its row and column.