alinea
Version:
Headless git-based CMS
47 lines (45 loc) • 1.41 kB
JavaScript
import {
rgbaToThumbHash,
thumbHashToAverageRGBA
} from "../../chunks/chunk-GWZU2AWQ.js";
import {
I,
m
} from "../../chunks/chunk-76QF5YTJ.js";
import "../../chunks/chunk-NZLE2WMY.js";
// src/core/media/CreatePreview.ts
import { base64 } from "../util/Encoding.js";
async function createPreview(blob) {
const { default: sharp } = await import("sharp").catch(() => {
throw new Error(
`To create image previews server side you need to install the 'sharp' package`
);
});
const image = sharp(await blob.arrayBuffer());
const metadata = await image.metadata();
const width = metadata.width ?? 0;
const height = metadata.height ?? 0;
const scaledImage = image.resize(100, 100, {
fit: "inside"
});
const { data, info } = await scaledImage.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
const thumbHash = rgbaToThumbHash(info.width, info.height, data);
const { r, g, b, a } = thumbHashToAverageRGBA(thumbHash);
const averageColor = I(m(r * 255, g * 255, b * 255, a));
const previewImage = image.resize(160, 160, {
fit: "inside"
});
const previewBuffer = await previewImage.webp().toBuffer();
const preview = `data:image/webp;base64,${previewBuffer.toString("base64")}`;
return {
width,
height,
thumbHash: base64.stringify(thumbHash),
averageColor,
preview,
focus: { x: 0.5, y: 0.5 }
};
}
export {
createPreview
};