feat: make thumbhash work with image slider
Some checks failed
Deploy to SFTP Server / build (push) Has been cancelled

This commit is contained in:
2024-04-06 23:40:31 +02:00
parent 68431e6b9c
commit 96c053d5ff
10 changed files with 126 additions and 68 deletions

34
src/helpers/image.ts Normal file
View File

@ -0,0 +1,34 @@
let loadingSharp = false;
import { rgbaToThumbHash } from "thumbhash";
export async function generateThumbHash(image: { width: number, height: number }) {
if (!loadingSharp) {
loadingSharp = true;
setTimeout(async () => {
// @ts-ignore
globalThis["sharp"] = (await import("sharp")).default;
}, 1000);
return;
}
// @ts-ignore
const sharp = globalThis["sharp"] as typeof import("sharp");
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");
}