← 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
/**
* Minimal PNG decoder built on the platform's DecompressionStream, so it needs
* no npm zlib (which bundlers resolve to Node builds that Workers can't load).
* Handles every non-interlaced PNG: gray, RGB, palette, gray+alpha, RGBA at
* 1–16 bits, plus palette transparency. Transparency is flattened onto white.
*/
export type DecodedPng = { data: Uint8Array; width: number; height: number }
const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
const channelsByColorType: Record<number, number> = {
0: 1,
2: 3,
3: 1,
4: 2,
6: 4,
}
export function readPngSize(bytes: Uint8Array) {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
if (bytes.length < 24 || signature.some((value, i) => bytes[i] !== value)) {
throw new Error('This PNG is damaged or incomplete.')
}
return { width: view.getUint32(16), height: view.getUint32(20) }
}
export async function decodePng(bytes: Uint8Array): Promise<DecodedPng> {
const { width, height } = readPngSize(bytes)
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
const depth = bytes[24]!
const colorType = bytes[25]!
const channels = channelsByColorType[colorType]
if (!channels) throw new Error('This PNG uses an unknown color type.')
if (bytes[28] !== 0) {
throw new Error(
'Interlaced PNGs are not supported. Re-save it without interlacing, or as JPEG.',
)
}
const idat: Array<Uint8Array> = []
let palette: Uint8Array | undefined
let paletteAlpha: Uint8Array | undefined
for (let offset = 8; offset + 8 <= bytes.length;) {
const length = view.getUint32(offset)
const type = String.fromCharCode(...bytes.subarray(offset + 4, offset + 8))
const body = bytes.subarray(offset + 8, offset + 8 + length)
if (type === 'IDAT') idat.push(body)
else if (type === 'PLTE') palette = body
else if (type === 'tRNS') paletteAlpha = body
else if (type === 'IEND') break
offset += 12 + length
}
if (colorType === 3 && !palette) {
throw new Error('This PNG is missing its color palette.')
}
const raw = await inflate(idat)
const bitsPerPixel = channels * depth
const stride = Math.ceil((width * bitsPerPixel) / 8)
const bytesPerPixel = Math.max(1, bitsPerPixel >> 3)
if (raw.length < (stride + 1) * height) {
throw new Error('This PNG is damaged or incomplete.')
}
const rows = unfilter(raw, stride, height, bytesPerPixel)
const out = new Uint8Array(width * height * 4)
const max = (1 << Math.min(depth, 8)) - 1
const sample = (row: Uint8Array, index: number) => {
if (depth === 16) return row[index * 2]!
if (depth === 8) return row[index]!
const perByte = 8 / depth
const shift = 8 - depth * ((index % perByte) + 1)
const value = (row[Math.floor(index / perByte)]! >> shift) & max
return colorType === 3 ? value : Math.round((value * 255) / max)
}
for (let y = 0; y < height; y += 1) {
const row = rows.subarray(y * stride, (y + 1) * stride)
for (let x = 0; x < width; x += 1) {
let r: number, g: number, b: number
let a = 255
if (colorType === 3) {
const entry = sample(row, x)
r = palette![entry * 3] ?? 0
g = palette![entry * 3 + 1] ?? 0
b = palette![entry * 3 + 2] ?? 0
a = paletteAlpha?.[entry] ?? 255
} else if (channels <= 2) {
r = g = b = sample(row, x * channels)
if (channels === 2) a = sample(row, x * 2 + 1)
} else {
r = sample(row, x * channels)
g = sample(row, x * channels + 1)
b = sample(row, x * channels + 2)
if (channels === 4) a = sample(row, x * 4 + 3)
}
const o = (y * width + x) * 4
const alpha = a / 255
out[o] = Math.round(r * alpha + 255 * (1 - alpha))
out[o + 1] = Math.round(g * alpha + 255 * (1 - alpha))
out[o + 2] = Math.round(b * alpha + 255 * (1 - alpha))
out[o + 3] = 255
}
}
return { data: out, width, height }
}
async function inflate(parts: Array<Uint8Array>): Promise<Uint8Array> {
const stream = new Blob(parts as Array<BlobPart>)
.stream()
.pipeThrough(new DecompressionStream('deflate'))
return new Uint8Array(await new Response(stream).arrayBuffer())
}
/** Undo PNG scanline filters in place; returns the rows without filter bytes. */
function unfilter(
raw: Uint8Array,
stride: number,
height: number,
bpp: number,
): Uint8Array {
const rows = new Uint8Array(stride * height)
for (let y = 0; y < height; y += 1) {
const filter = raw[y * (stride + 1)]!
const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
const at = y * stride
for (let x = 0; x < stride; x += 1) {
const left = x >= bpp ? rows[at + x - bpp]! : 0
const up = y > 0 ? rows[at - stride + x]! : 0
const upLeft = y > 0 && x >= bpp ? rows[at - stride + x - bpp]! : 0
let value = line[x]!
if (filter === 1) value += left
else if (filter === 2) value += up
else if (filter === 3) value += (left + up) >> 1
else if (filter === 4) value += paeth(left, up, upLeft)
rows[at + x] = value & 0xff
}
}
return rows
}
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
}