@nuxt/image
Version:
Nuxt Image Module
45 lines (44 loc) • 1.18 kB
JavaScript
export async function imageMeta(_ctx, url) {
const meta = await _imageMeta(url).catch((err) => {
console.error("Failed to get image meta for " + url, err + "");
return {
width: 0,
height: 0,
ratio: 0
};
});
return meta;
}
async function _imageMeta(url) {
if (import.meta.server) {
const imageMeta2 = await import("image-meta").then((r) => r.imageMeta);
const data = await fetch(url).then((res) => res.buffer());
const metadata = imageMeta2(data);
if (!metadata) {
throw new Error(`No metadata could be extracted from the image \`${url}\`.`);
}
const { width, height } = metadata;
const meta = {
width,
height,
ratio: width && height ? width / height : void 0
};
return meta;
}
if (typeof Image === "undefined") {
throw new TypeError("Image not supported");
}
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const meta = {
width: img.width,
height: img.height,
ratio: img.width / img.height
};
resolve(meta);
};
img.onerror = (err) => reject(err);
img.src = url;
});
}