codev / src /ink-picture /utils /jimpURL.ts
chenbhao's picture
fix: unify error message to "Failed to fetch" and exit on load failure
9ec41c1
Raw
History Blame Contribute Delete
815 Bytes
import { Jimp } from "jimp";
const SUPPORTED_MIME_TYPES = new Set([
"image/jpeg",
"image/png",
"image/gif",
"image/bmp",
"image/tiff",
"image/webp",
]);
export async function loadImageFromUrl(url: string) {
const response = await fetch(url, {
headers: {
Accept: "image/jpeg, image/png, image/gif, image/bmp, image/tiff, image/webp, */*",
},
});
if (!response.ok) {
throw new Error(`Failed to fetch: ${response.status}`);
}
const contentType = response.headers.get("Content-Type") ?? "";
const mime = contentType.split(";")[0].trim().toLowerCase();
if (mime && !SUPPORTED_MIME_TYPES.has(mime)) {
throw new Error("Failed to fetch");
}
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return Jimp.read(buffer);
}