Skip to content
Source
Sign inSign up

icon-export.ts

71 lines2.4 KB

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 };
27​
28export function encodePngIco(images: ReadonlyArray<PngIconImage>): Buffer {
29 if (images.length === 0) {
30 throw new Error("An ICO file requires at least one PNG rendition.");
31 }
32​
33 const seenSizes = new Set<number>();
34 for (const image of images) {
35 if (!Number.isInteger(image.size) || image.size < 1 || image.size > 256) {
36 throw new Error(`ICO rendition size must be an integer from 1 to 256, got ${image.size}.`);
37 }
38 if (seenSizes.has(image.size)) {
39 throw new Error(`ICO rendition size ${image.size} was provided more than once.`);
40 }
41 if (image.contents.length === 0) {
42 throw new Error(`ICO rendition ${image.size}x${image.size} is empty.`);
43 }
44 seenSizes.add(image.size);
45 }
46​
47 const headerSize = 6;
48 const directoryEntrySize = 16;
49 const directorySize = directoryEntrySize * images.length;
50 const header = Buffer.alloc(headerSize + directorySize);
51 header.writeUInt16LE(0, 0);
52 header.writeUInt16LE(1, 2);
53 header.writeUInt16LE(images.length, 4);
54​
55 let imageOffset = header.length;
56 images.forEach((image, index) => {
57 const entryOffset = headerSize + index * directoryEntrySize;
58 const encodedSize = image.size === 256 ? 0 : image.size;
59 header.writeUInt8(encodedSize, entryOffset);
60 header.writeUInt8(encodedSize, entryOffset + 1);
61 header.writeUInt8(0, entryOffset + 2);
62 header.writeUInt8(0, entryOffset + 3);
63 header.writeUInt16LE(1, entryOffset + 4);
64 header.writeUInt16LE(32, entryOffset + 6);
65 header.writeUInt32LE(image.contents.length, entryOffset + 8);
66 header.writeUInt32LE(imageOffset, entryOffset + 12);
67 imageOffset += image.contents.length;
68 });
69​
70 return Buffer.concat([header, ...images.map((image) => image.contents)]);