export type ImageInfo = { type: 'image/webp' | 'image/png' | 'image/jpeg'; ext: string; width: number; height: number }; /** Identify an image by magic bytes and read its pixel size from the header. */ export function sniffImage(b: Uint8Array): ImageInfo | null { const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); // PNG if (b.length > 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) { return { type: 'image/png', ext: 'png', width: dv.getUint32(16), height: dv.getUint32(20) }; } // JPEG: walk segments to the first start-of-frame marker if (b.length > 4 && b[0] === 0xff && b[1] === 0xd8) { let i = 2; while (i + 9 < b.length) { if (b[i] !== 0xff) return null; const marker = b[i + 1]; if (marker === 0xff) { i++; continue; } const len = dv.getUint16(i + 2); if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) { return { type: 'image/jpeg', ext: 'jpg', width: dv.getUint16(i + 7), height: dv.getUint16(i + 5) }; } i += 2 + len; } return null; } // WebP if (b.length > 30 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) { const fourcc = String.fromCharCode(b[12], b[13], b[14], b[15]); if (fourcc === 'VP8 ') { return { type: 'image/webp', ext: 'webp', width: dv.getUint16(26, true) & 0x3fff, height: dv.getUint16(28, true) & 0x3fff }; } if (fourcc === 'VP8L') { const bits = dv.getUint32(21, true); return { type: 'image/webp', ext: 'webp', width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }; } if (fourcc === 'VP8X') { const w = 1 + (b[24] | (b[25] << 8) | (b[26] << 16)); const h = 1 + (b[27] | (b[28] << 8) | (b[29] << 16)); return { type: 'image/webp', ext: 'webp', width: w, height: h }; } } return null; }