feat: add thumbhash loading to image
Some checks failed
Deploy to SFTP Server / build (push) Failing after 1m18s
Some checks failed
Deploy to SFTP Server / build (push) Failing after 1m18s
This commit is contained in:
@@ -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
|
||||
|
Reference in New Issue
Block a user