/** * 极简 PNG 编码器(RGB 8-bit,无压缩滤波)— 验证码图片专用。 * node:zlib + 手写 CRC32,零依赖;输出为标准 PNG。 */ import zlib from "node:zlib"; const CRC_TABLE = (() => { const table = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) { c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; } table[n] = c >>> 0; } return table; })(); function crc32(buf: Buffer): number { let c = 0xffffffff; for (let i = 0; i < buf.length; i++) { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); } return (c ^ 0xffffffff) >>> 0; } function chunk(type: string, data: Buffer): Buffer { const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0); const typeBuf = Buffer.from(type, "ascii"); const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0); return Buffer.concat([len, typeBuf, data, crc]); } export function encodePng( width: number, height: number, rgb: Uint8Array ): Buffer { const rowBytes = width * 3; const raw = Buffer.alloc((rowBytes + 1) * height); for (let y = 0; y < height; y++) { raw[y * (rowBytes + 1)] = 0; // filter: none raw.set( rgb.subarray(y * rowBytes, (y + 1) * rowBytes), y * (rowBytes + 1) + 1 ); } const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(height, 4); ihdr[8] = 8; // bit depth ihdr[9] = 2; // color type: truecolor RGB const sig = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); return Buffer.concat([ sig, chunk("IHDR", ihdr), chunk("IDAT", zlib.deflateSync(raw, { level: 9 })), chunk("IEND", Buffer.alloc(0)), ]); }