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

View File

@@ -1,40 +1,20 @@
---
import type { ImageMetadata } from "astro";
import { Picture as AstroImage } from "astro:assets";
import { generateThumbHash } from "@helpers/image";
interface Props {
src: ImageMetadata;
alt: string;
class?: string;
caption?: string;
hash?: boolean;
loader?: boolean;
maxWidth?: number;
}
import { rgbaToThumbHash } from "thumbhash";
const { src: image, hash = true, alt, maxWidth } = Astro.props;
const { src: image, loader = true, hash = true, alt, maxWidth } = Astro.props;
let thumbhash = "";
const s = await import("sharp");
const sharp = s.default;
if (hash) {
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);
thumbhash = Buffer.from(buffer).toString("base64");
}
let thumbhash = hash ? await generateThumbHash(image) : "";
const sizes = [
{
@@ -59,7 +39,9 @@ const sizes = [
src={image}
alt={alt}
data-thumbhash={thumbhash}
pictureAttributes={{ class: hash ? "block h-full relative" : "" }}
pictureAttributes={{
class: `${hash ? "block h-full relative" : ""} ${loader ? "thumb" : ""}`,
}}
class={Astro.props.class}
widths={sizes.map((size) => size.width)}
sizes={sizes