import { deflateSync } from "node:zlib"; import { mkdirSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; export function writeRgbaPng (filePath, width, height, pixels) { const raw = Buffer.alloc((width * 4 + 1) * height); for (let y = 0; y < height; y++) { raw[y * (width * 4 + 1)] = 0; Buffer.from(pixels).copy(raw, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4); } const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(height, 4); ihdr[8] = 8; ihdr[9] = 6; const png = Buffer.concat([ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0)) ]); mkdirSync(dirname(filePath), { recursive: true }); writeFileSync(filePath, png); } export function makeRgba (width, height, fill = [0, 0, 0, 0]) { const pixels = Buffer.alloc(width * height * 4); for (let i = 0; i < width * height; i++) { pixels.set(fill, i * 4); } return { width, height, pixels }; } export function fillRect (image, x, y, width, height, rgba) { for (let py = y; py < y + height; py++) { for (let px = x; px < x + width; px++) { if (px < 0 || py < 0 || px >= image.width || py >= image.height) { continue; } image.pixels.set(rgba, (py * image.width + px) * 4); } } } function chunk (type, data) { const name = Buffer.from(type); const payload = Buffer.concat([name, data]); const header = Buffer.alloc(4); header.writeUInt32BE(data.length, 0); const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(payload), 0); return Buffer.concat([header, payload, crc]); } function crc32 (buffer) { let crc = 0xffffffff; for (const byte of buffer) { crc ^= byte; for (let i = 0; i < 8; i++) { crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); } } return (crc ^ 0xffffffff) >>> 0; }