Encodes grayscale Uint8Array pixels into a complete PNG byte stream with IHDR, zlib-compressed IDAT scanlines, and IEND chunk.
export async function encodeGrayPng(pixels: Uint8Array, width: number, height: number): Promise<Uint8Array> {
if (pixels.length !== width * height) {
throw new Error(`encodeGrayPng: pixels.length=${pixels.length} != ${width}×${height}=${width * height}`);
}
// IHDR: width(4) height(4) bitDepth=8 colorType=0(gray) compress=0 filter=0 interlace=0
const ihdr = new Uint8Array(13);
ihdr.set(u32be(width), 0);
ihdr.set(u32be(height), 4);
ihdr[8] = 8;
ihdr[9] = 0; // colorType 0 = grayscale; bytes 10-12 already zero
// Prepend per-scanline filter byte (0 = None).
const stride = width + 1;
const raw = new Uint8Array(stride * height);
for (let y = 0; y < height; y++) {
raw[y * stride] = 0; // filter: None
raw.set(pixels.subarray(y * width, (y + 1) * width), y *
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search 40K more like it.
Get a free API key