| 1 | import { deflateSync } from "node:zlib"; |
| 2 | import { mkdirSync, writeFileSync } from "node:fs"; |
| 3 | import { dirname } from "node:path"; |
| 4 | |
| 5 | export function writeRgbaPng (filePath, width, height, pixels) |
| 6 | { |
| 7 | const raw = Buffer.alloc((width * 4 + 1) * height); |
| 8 | for (let y = 0; y < height; y++) |
| 9 | { |
| 10 | raw[y * (width * 4 + 1)] = 0; |
| 11 | Buffer.from(pixels).copy(raw, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4); |
| 12 | } |
| 13 | const ihdr = Buffer.alloc(13); |
| 14 | ihdr.writeUInt32BE(width, 0); |
| 15 | ihdr.writeUInt32BE(height, 4); |
| 16 | ihdr[8] = 8; |
| 17 | ihdr[9] = 6; |
| 18 | const png = Buffer.concat([ |
| 19 | Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), |
| 20 | chunk("IHDR", ihdr), |
| 21 | chunk("IDAT", deflateSync(raw)), |
| 22 | chunk("IEND", Buffer.alloc(0)) |
| 23 | ]); |
| 24 | mkdirSync(dirname(filePath), { recursive: true }); |
| 25 | writeFileSync(filePath, png); |
| 26 | } |
| 27 | |
| 28 | export function makeRgba (width, height, fill = [0, 0, 0, 0]) |
| 29 | { |
| 30 | const pixels = Buffer.alloc(width * height * 4); |
| 31 | for (let i = 0; i < width * height; i++) |
| 32 | { pixels.set(fill, i * 4); } |
| 33 | return { width, height, pixels }; |
| 34 | } |
| 35 | |
| 36 | export function fillRect (image, x, y, width, height, rgba) |
| 37 | { |
| 38 | for (let py = y; py < y + height; py++) |
| 39 | { |
| 40 | for (let px = x; px < x + width; px++) |
| 41 | { |
| 42 | if (px < 0 || py < 0 || px >= image.width || py >= image.height) |
| 43 | { continue; } |
| 44 | image.pixels.set(rgba, (py * image.width + px) * 4); |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | function chunk (type, data) |
| 50 | { |
| 51 | const name = Buffer.from(type); |
| 52 | const payload = Buffer.concat([name, data]); |
| 53 | const header = Buffer.alloc(4); |
| 54 | header.writeUInt32BE(data.length, 0); |
| 55 | const crc = Buffer.alloc(4); |
| 56 | crc.writeUInt32BE(crc32(payload), 0); |
| 57 | return Buffer.concat([header, payload, crc]); |
| 58 | } |
| 59 | |
| 60 | function crc32 (buffer) |
| 61 | { |
| 62 | let crc = 0xffffffff; |
| 63 | for (const byte of buffer) |
| 64 | { |
| 65 | crc ^= byte; |
| 66 | for (let i = 0; i < 8; i++) |
| 67 | { crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); } |
| 68 | } |
| 69 | return (crc ^ 0xffffffff) >>> 0; |
| 70 | } |