Branchwell

Skillfarm / website · skillfarm.ai / src / lib / images.ts

Raw 1.9 KB on 947b01baffc181407e99132c54709fba5e84ae85
1export type ImageInfo = { type: 'image/webp' | 'image/png' | 'image/jpeg'; ext: string; width: number; height: number };
2
3/** Identify an image by magic bytes and read its pixel size from the header. */
4export function sniffImage(b: Uint8Array): ImageInfo | null {
5 const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
6 // PNG
7 if (b.length > 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {
8 return { type: 'image/png', ext: 'png', width: dv.getUint32(16), height: dv.getUint32(20) };
9 }
10 // JPEG: walk segments to the first start-of-frame marker
11 if (b.length > 4 && b[0] === 0xff && b[1] === 0xd8) {
12 let i = 2;
13 while (i + 9 < b.length) {
14 if (b[i] !== 0xff) return null;
15 const marker = b[i + 1];
16 if (marker === 0xff) { i++; continue; }
17 const len = dv.getUint16(i + 2);
18 if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
19 return { type: 'image/jpeg', ext: 'jpg', width: dv.getUint16(i + 7), height: dv.getUint16(i + 5) };
20 }
21 i += 2 + len;
22 }
23 return null;
24 }
25 // WebP
26 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) {
27 const fourcc = String.fromCharCode(b[12], b[13], b[14], b[15]);
28 if (fourcc === 'VP8 ') {
29 return { type: 'image/webp', ext: 'webp', width: dv.getUint16(26, true) & 0x3fff, height: dv.getUint16(28, true) & 0x3fff };
30 }
31 if (fourcc === 'VP8L') {
32 const bits = dv.getUint32(21, true);
33 return { type: 'image/webp', ext: 'webp', width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
34 }
35 if (fourcc === 'VP8X') {
36 const w = 1 + (b[24] | (b[25] << 8) | (b[26] << 16));
37 const h = 1 + (b[27] | (b[28] << 8) | (b[29] << 16));
38 return { type: 'image/webp', ext: 'webp', width: w, height: h };
39 }
40 }
41 return null;
42}