forked from mtusi2026/mtusi2026lab4
96 lines
2.5 KiB
TypeScript
96 lines
2.5 KiB
TypeScript
import { randomBytes } from 'node:crypto';
|
|
import { crc32, deflateSync } from 'node:zlib';
|
|
|
|
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
|
|
function chunk(type: string, data: Buffer): Buffer {
|
|
const head = Buffer.alloc(8);
|
|
head.writeUInt32BE(data.length, 0);
|
|
head.write(type, 4, 'latin1');
|
|
const crc = Buffer.alloc(4);
|
|
crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0);
|
|
return Buffer.concat([head, data, crc]);
|
|
}
|
|
|
|
export function buildPng(options: {
|
|
width: number;
|
|
height: number;
|
|
colorType: number;
|
|
bitDepth: number;
|
|
idat: Buffer;
|
|
}): Buffer {
|
|
const ihdr = Buffer.alloc(13);
|
|
ihdr.writeUInt32BE(options.width, 0);
|
|
ihdr.writeUInt32BE(options.height, 4);
|
|
ihdr[8] = options.bitDepth;
|
|
ihdr[9] = options.colorType;
|
|
return Buffer.concat([
|
|
SIGNATURE,
|
|
chunk('IHDR', ihdr),
|
|
chunk('IDAT', options.idat),
|
|
chunk('IEND', Buffer.alloc(0)),
|
|
]);
|
|
}
|
|
|
|
/** Inserts a private ancillary chunk before IEND to reach exactly `size` bytes. */
|
|
export function padPngTo(png: Buffer, size: number): Buffer {
|
|
const extra = size - png.length;
|
|
if (extra === 0) return png;
|
|
if (extra < 12) throw new Error('PNG padding needs at least 12 bytes');
|
|
const iend = png.length - 12;
|
|
return Buffer.concat([
|
|
png.subarray(0, iend),
|
|
chunk('prVt', Buffer.alloc(extra - 12)),
|
|
png.subarray(iend),
|
|
]);
|
|
}
|
|
|
|
/** 8000x5001 grayscale 1-bit, all-zero rows: tiny file, 40 008 000 pixels. */
|
|
export function pixelBombPng(): Buffer {
|
|
const width = 8000;
|
|
const height = 5001;
|
|
const row = Buffer.alloc(1 + Math.ceil(width / 8));
|
|
const raw = Buffer.alloc(row.length * height);
|
|
return buildPng({
|
|
width,
|
|
height,
|
|
colorType: 0,
|
|
bitDepth: 1,
|
|
idat: deflateSync(raw, { level: 9 }),
|
|
});
|
|
}
|
|
|
|
const NOISE_WIDTH = 1024;
|
|
const NOISE_ROW = 1 + NOISE_WIDTH * 3;
|
|
|
|
function noiseOfHeight(height: number): Buffer {
|
|
const raw = randomBytes(NOISE_ROW * height);
|
|
for (let row = 0; row < height; row += 1) raw[row * NOISE_ROW] = 0;
|
|
return buildPng({
|
|
width: NOISE_WIDTH,
|
|
height,
|
|
colorType: 2,
|
|
bitDepth: 8,
|
|
idat: deflateSync(raw, { level: 0 }),
|
|
});
|
|
}
|
|
|
|
/** Incompressible, structurally valid PNG of exactly `size` bytes. */
|
|
export function noisePng(size: number): Buffer {
|
|
let height = Math.max(1, Math.floor(size / NOISE_ROW));
|
|
for (;;) {
|
|
const png = noiseOfHeight(height);
|
|
if (png.length > size) {
|
|
height -= 1;
|
|
if (height < 1) throw new Error('size is too small for noisePng');
|
|
continue;
|
|
}
|
|
const extra = size - png.length;
|
|
if (extra > 0 && extra < 12) {
|
|
height -= 1;
|
|
continue;
|
|
}
|
|
return padPngTo(png, size);
|
|
}
|
|
}
|