This component works just like the original image from astro:assets
, however it comes with responsive image generation.
Make sure to install peer deps for blur placeholder to work.
pnpm install lqip-modern
It must be used with dynamic image data like so:
---
import Image from "@/components/image";
// Your local image
import localImg from "@/assets/my-local.jpg" // My extra large image 1920x1080
---
<Image src={localImg} alt="original" /> // Load full resolution image, but downscale based on viewport size
/*
* Set the maximum generated width to 400px
* If a screen is 320px wide, browser will load 320px wide image.
*/
<Image src={localImg} width={800} alt="smaller" class="w-full" />
/**
* Tell browser this image is 50% of the viewport width
* Browser will figure out what width to generate.
* I.e if laptop@1280 -> 640px is loaded, if desktop@1920 -> 1200px is loaded
*/
<Image src={localImg} sizes="50vw" alt="half-screen" class="w-full" />
Avoid white image of death and apply a 16px blurred placeholder using lqip-modern.
<Image placeholder="blur" src={localImg} sizes="50vw" alt="half-screen" class="w-full" />
In order to improve build times you can optionally use Vercel's image service for the assets. Now the Image
component will function exactly like Next.js' Image minus their layout prop.
// astro.config.mjs
{
// ...config
adapter: vercel({
imageService: true
}),
}
Great solution ! If only they merged it into Astro 😞 There's also https://github.com/RafidMuhymin/astro-imagetools but I think it's been abandoned.
Tiny fix for win (needed for other os's ?):
https://gist.github.com/sannajammeh/d1dfddc8c2538062de53714b07953cdf#file-loadableimage-astro-L34
And removed SCSS directive since there's no need for it:
https://gist.github.com/sannajammeh/d1dfddc8c2538062de53714b07953cdf#file-loadableimage-astro-L71
Found this rust alternative to create the placeholders https://rodneylab.com/astro-picture-component/#trophy-level-it-up-low-resolution-placeholder