1const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
2
3export const WINDOWS_ICON_SIZES = [16, 24, 32, 48, 64, 128, 256] as const;
4
5export interface PngIconImage {
6 readonly size: number;
7 readonly contents: Buffer;
8}
9
10export function readPngDimensions(contents: Buffer): {
11 readonly width: number;
12 readonly height: number;
13} {
14 if (
15 contents.length < 24 ||
16 !contents.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) ||
17 contents.toString("ascii", 12, 16) !== "IHDR"
18 ) {
19 throw new Error("Icon Composer produced an invalid PNG.");
20 }
21
22 return {
23 width: contents.readUInt32BE(16),
24 height: contents.readUInt32BE(20),
25 };
26}
27
28/** Encodes PNG renditions directly into a modern, multi-resolution ICO file. */
29export function encodePngIco(images: ReadonlyArray<PngIconImage>): Buffer {
30 if (images.length === 0) {
31 throw new Error("An ICO file requires at least one PNG rendition.");
32 }
33
34 const seenSizes = new Set<number>();
35 for (const image of images) {
36 if (!Number.isInteger(image.size) || image.size < 1 || image.size > 256) {
37 throw new Error(`ICO rendition size must be an integer from 1 to 256, got ${image.size}.`);
38 }
39 if (seenSizes.has(image.size)) {
40 throw new Error(`ICO rendition size ${image.size} was provided more than once.`);
41 }
42 if (image.contents.length === 0) {
43 throw new Error(`ICO rendition ${image.size}x${image.size} is empty.`);
44 }
45 seenSizes.add(image.size);
46 }
47
48 const headerSize = 6;
49 const directoryEntrySize = 16;
50 const directorySize = directoryEntrySize * images.length;
51 const header = Buffer.alloc(headerSize + directorySize);
52 header.writeUInt16LE(0, 0);
53 header.writeUInt16LE(1, 2);
54 header.writeUInt16LE(images.length, 4);
55
56 let imageOffset = header.length;
57 images.forEach((image, index) => {
58 const entryOffset = headerSize + index * directoryEntrySize;
59 const encodedSize = image.size === 256 ? 0 : image.size;
60 header.writeUInt8(encodedSize, entryOffset);
61 header.writeUInt8(encodedSize, entryOffset + 1);
62 header.writeUInt8(0, entryOffset + 2);
63 header.writeUInt8(0, entryOffset + 3);
64 header.writeUInt16LE(1, entryOffset + 4);
65 header.writeUInt16LE(32, entryOffset + 6);
66 header.writeUInt32LE(image.contents.length, entryOffset + 8);
67 header.writeUInt32LE(imageOffset, entryOffset + 12);
68 imageOffset += image.contents.length;
69 });
70
71 return Buffer.concat([header, ...images.map((image) => image.contents)]);
72}