← Public packages
@kentcdodds/photo-portfolio
A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.
Files
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { deflateSync } from 'node:zlib'
import { decodePng } from '../src/images/png.ts'
/**
* Encode a PNG from raw scanlines, cycling through all five filter types so
* the decoder's unfiltering is exercised on every row.
*/
function encodePng(options: {
width: number
height: number
depth: number
colorType: number
rows: Array<Uint8Array>
palette?: Array<number>
transparency?: Array<number>
}) {
const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[options.colorType]!
const bpp = Math.max(1, (channels * options.depth) >> 3)
const filtered: Array<number> = []
options.rows.forEach((row, y) => {
const previous = options.rows[y - 1]
const filter = y % 5
filtered.push(filter)
row.forEach((value, x) => {
const left = x >= bpp ? row[x - bpp]! : 0
const up = previous?.[x] ?? 0
const upLeft = x >= bpp ? (previous?.[x - bpp] ?? 0) : 0
const predictor = [
0,
left,
up,
(left + up) >> 1,
paeth(left, up, upLeft),
][filter]!
filtered.push((value - predictor) & 0xff)
})
})
const header = Buffer.alloc(13)
header.writeUInt32BE(options.width, 0)
header.writeUInt32BE(options.height, 4)
header.set([options.depth, options.colorType, 0, 0, 0], 8)
return new Uint8Array(
Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', header),
...(options.palette ? [chunk('PLTE', Buffer.from(options.palette))] : []),
...(options.transparency
? [chunk('tRNS', Buffer.from(options.transparency))]
: []),
chunk('IDAT', deflateSync(Buffer.from(filtered))),
chunk('IEND', Buffer.alloc(0)),
]),
)
}
function chunk(type: string, body: Buffer) {
const length = Buffer.alloc(4)
length.writeUInt32BE(body.length)
// The decoder ignores CRCs, so a zero CRC keeps the fixture short.
return Buffer.concat([
length,
Buffer.from(type, 'latin1'),
body,
Buffer.alloc(4),
])
}
function paeth(a: number, b: number, c: number) {
const p = a + b - c
const pa = Math.abs(p - a)
const pb = Math.abs(p - b)
const pc = Math.abs(p - c)
if (pa <= pb && pa <= pc) return a
return pb <= pc ? b : c
}
const rgbAt = (x: number, y: number) => [
(x * 37 + y * 11) & 0xff,
(x * 5 + y * 53) & 0xff,
(x * y + 90) & 0xff,
]
test('decodes 8-bit RGBA across every filter type and flattens alpha onto white', async () => {
const width = 9
const height = 10
const rows = Array.from({ length: height }, (_, y) =>
Uint8Array.from(
Array.from({ length: width }, (_, x) => [
...rgbAt(x, y),
x === 0 ? 0 : 255,
]).flat(),
),
)
const png = await decodePng(
encodePng({ width, height, depth: 8, colorType: 6, rows }),
)
assert.deepEqual([png.width, png.height], [width, height])
for (let y = 0; y < height; y += 1) {
for (let x = 0; x < width; x += 1) {
const o = (y * width + x) * 4
const expected = x === 0 ? [255, 255, 255, 255] : [...rgbAt(x, y), 255]
assert.deepEqual([...png.data.subarray(o, o + 4)], expected, `${x},${y}`)
}
}
})
test('decodes 16-bit RGB by keeping the high byte', async () => {
const rows = Array.from({ length: 6 }, (_, y) =>
Uint8Array.from(
Array.from({ length: 4 }, (_, x) =>
rgbAt(x, y).flatMap((value) => [value, 0x7f]),
).flat(),
),
)
const png = await decodePng(
encodePng({ width: 4, height: 6, depth: 16, colorType: 2, rows }),
)
assert.deepEqual(
[...png.data.subarray(4 * 5, 4 * 5 + 4)],
[...rgbAt(1, 1), 255],
)
})
test('decodes 4-bit palette images with transparency and 1-bit grayscale', async () => {
const palette = await decodePng(
encodePng({
width: 3,
height: 5,
depth: 4,
colorType: 3,
// Indices 0,1,2 packed two per byte (padding nibble at the end).
rows: Array.from({ length: 5 }, () => Uint8Array.from([0x01, 0x20])),
palette: [10, 20, 30, 200, 100, 50, 0, 0, 0],
transparency: [255, 255, 0],
}),
)
assert.deepEqual(
[...palette.data.subarray(0, 12)],
[10, 20, 30, 255, 200, 100, 50, 255, 255, 255, 255, 255],
)
const gray = await decodePng(
encodePng({
width: 10,
height: 5,
depth: 1,
colorType: 0,
rows: Array.from({ length: 5 }, () =>
Uint8Array.from([0b10100000, 0b01000000]),
),
}),
)
const firstRow = Array.from({ length: 10 }, (_, x) => gray.data[x * 4])
assert.deepEqual(firstRow, [255, 0, 255, 0, 0, 0, 0, 0, 0, 255])
})
test('explains why interlaced PNGs are refused', async () => {
const bytes = encodePng({
width: 1,
height: 1,
depth: 8,
colorType: 0,
rows: [Uint8Array.from([0])],
})
bytes[28] = 1
await assert.rejects(decodePng(bytes), /Interlaced PNGs are not supported/)
})