Open History to see the last commit
1import { readImageDimensions } from "@t3tools/shared/imageDimensions";
2
3const ICNS_HEADER_BYTES = 8;
4const ICNS_MAGIC = 0x69636e73;
5const PNG_MAGIC = 0x89504e47;
6
7/**
8 * Returns a copy so the response does not pin the whole `.icns` buffer.
9 */
10export function extractIcnsPng(bytes: Uint8Array, minSize: number): Uint8Array | null {
11 const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
12 if (bytes.length < ICNS_HEADER_BYTES || data.getUint32(0) !== ICNS_MAGIC) return null;
13 const end = Math.min(data.getUint32(4), bytes.length);
14 let best: { readonly png: Uint8Array; readonly width: number } | null = null;
15 for (let offset = ICNS_HEADER_BYTES; offset + ICNS_HEADER_BYTES <= end;) {
16 const length = data.getUint32(offset + 4);
17 if (length < ICNS_HEADER_BYTES || offset + length > end) break;
18 const entry = bytes.subarray(offset + ICNS_HEADER_BYTES, offset + length);
19 const isPng = entry.length >= 4 && data.getUint32(offset + ICNS_HEADER_BYTES) === PNG_MAGIC;
20 offset += length;
21 const width = isPng ? readImageDimensions(entry)?.width : undefined;
22 if (width === undefined) continue;
23 const isBetter =
24 best === null ||
25 (best.width < minSize ? width > best.width : width >= minSize && width < best.width);
26 if (isBetter) best = { png: entry, width };
27 }
28 return best?.png.slice() ?? null;
29}