Files
chatgpt-imagegen-mcp/test/helpers.ts
T

45 lines
1.5 KiB
TypeScript

import { deflateSync } from "node:zlib";
const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
let c = n;
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
return c >>> 0;
});
export function crc32(data: Buffer): number {
let c = 0xffffffff;
for (const byte of data) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type: string, data: Buffer): Buffer {
const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(body));
return Buffer.concat([length, body, crc]);
}
/** Minimal valid 8-bit RGB PNG filled with one colour. */
export function makePng(width: number, height: number, rgb: [number, number, number] = [200, 60, 60]): Buffer {
const header = Buffer.alloc(13);
header.writeUInt32BE(width, 0);
header.writeUInt32BE(height, 4);
header[8] = 8; // bit depth
header[9] = 2; // colour type: RGB
const row = Buffer.alloc(1 + width * 3);
for (let x = 0; x < width; x += 1) row.set(rgb, 1 + x * 3);
const raw = Buffer.concat(Array.from({ length: height }, () => row));
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk("IHDR", header),
chunk("IDAT", deflateSync(raw)),
chunk("IEND", Buffer.alloc(0)),
]);
}
export function pngDataUri(width: number, height: number): string {
return `data:image/png;base64,${makePng(width, height).toString("base64")}`;
}