website/src/helpers/image.ts
Max Richter c513605de6
All checks were successful
Deploy to SFTP Server / build (push) Successful in 21m19s
fix: some stupid issue with sharp
2024-04-07 19:02:03 +02:00

45 lines
1.1 KiB
TypeScript

let loadingSharp = false;
import { rgbaToThumbHash } from "thumbhash";
let s: typeof import("sharp") | undefined;
async function getSharp(): Promise<typeof import("sharp") | undefined> {
if (s) return s;
if (import.meta.env.MODE !== "development") {
s = (await import("sharp")).default;
return s;
}
if (!loadingSharp) {
loadingSharp = true;
setTimeout(async () => {
s = (await import("sharp")).default;
}, 1000);
return;
}
}
export async function generateThumbHash(image: { width: number, height: number }) {
const sharp = await getSharp();
if (!sharp) return;
const scaleFactor = 100 / Math.max(image.width, image.height);
const smallWidth = Math.floor(image.width * scaleFactor);
const smallHeight = Math.floor(image.height * scaleFactor);
//@ts-ignore
const smallImg = await sharp(image.fsPath)
.resize(smallWidth, smallHeight)
.withMetadata()
.raw()
.ensureAlpha()
.toBuffer();
const buffer = rgbaToThumbHash(smallWidth, smallHeight, smallImg);
return Buffer.from(buffer).toString("base64");
}