feat: add thumbhash loading to image
Some checks failed
Deploy to SFTP Server / build (push) Failing after 1m18s

This commit is contained in:
2024-04-06 20:32:32 +02:00
parent 82eb0657e2
commit 5d59e2171d
7 changed files with 358 additions and 862 deletions

View File

@@ -6,10 +6,32 @@ interface Props {
alt: string;
class?: string;
caption?: string;
hash?: boolean;
maxWidth?: number;
}
import { rgbaToThumbHash } from "thumbhash";
import sharp from "sharp";
const { src: image, alt, maxWidth } = Astro.props;
const { src: image, hash = true, alt, maxWidth } = Astro.props;
let thumbhash = "";
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);
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");
}
const sizes = [
{
@@ -33,6 +55,8 @@ const sizes = [
<AstroImage
src={image}
alt={alt}
data-thumbhash={thumbhash}
pictureAttributes={{ class: hash ? "block h-full" : "" }}
class={Astro.props.class}
widths={sizes.map((size) => size.width)}
sizes={sizes