website-astro/src/components/AstroImage.astro

45 lines
1000 B
Plaintext

---
import { Image, getImage } from "astro:assets";
const { src, alt, width, height, ...attrs } = Astro.props;
// if h/w attributes are declared, use them. If not, use from the source file
const imgHeight = height ? height : src.height;
const imgWidth = width ? width : src.width;
// compute avif and webp format in order to use inside a <picture> element
const imgAvif = await getImage({
src: src,
format: "avif",
width: Number(imgWidth),
height: Number(imgHeight),
});
const imgWebp = await getImage({
src: src,
format: "webp",
width: Number(imgWidth),
height: Number(imgHeight),
});
---
<picture>
<source
srcset={imgAvif.src}
sizes={`(max-inline-size: ${imgWidth}px) 100vw, ${imgHeight}px`}
type="image/avif"
/>
<source
srcset={imgWebp.src}
sizes={`(max-inline-size: ${imgWidth}px) 100vw, ${imgHeight}px`}
type="image/webp"
/>
<Image
src={src}
width={Number(imgWidth)}
height={Number(imgHeight)}
format="jpg"
alt={alt ? alt : ""}
{...attrs}
/>
</picture>