1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
// Decoding image files into canvases. The browser handles PNG/JPEG/GIF/WebP/BMP/ICO/AVIF/SVG;
// TIFF is decoded in JS.
import { blobToImage, createCanvas } from '../core/util.js';
import { isTIFF, decodeTIFF } from './encoders/tiff.js';
export const IMAGE_ACCEPT = 'image/*,.tif,.tiff,.ico,.bmp,.svg';
const MAX_PIXELS = 12000 * 12000;
/** Decode a File/Blob into a canvas. */
export async function decodeImageFile(file) {
const head = new Uint8Array(await file.slice(0, 8).arrayBuffer());
if (isTIFF(head)) {
const id = decodeTIFF(await file.arrayBuffer());
const c = createCanvas(id.width, id.height);
c.getContext('2d').putImageData(id, 0, 0);
return c;
}
let img;
try {
img = await blobToImage(file);
} catch {
throw new Error(`Could not open “${file.name || 'image'}”: unsupported or corrupt image`);
}
let w = img.naturalWidth || img.width, h = img.naturalHeight || img.height;
if (!w || !h) { w = 1024; h = 1024; } // SVG without intrinsic size
if (w * h > MAX_PIXELS) throw new Error(`Image is too large (${w}×${h})`);
const c = createCanvas(w, h);
c.getContext('2d').drawImage(img, 0, 0, w, h);
return c;
}
export function isImageFile(file) {
return /^image\//.test(file.type) || /\.(png|jpe?g|gif|webp|bmp|ico|tiff?|svg|avif)$/i.test(file.name || '');
}
|