#Responsive image with <Picture /> component

4 messages · Page 1 of 1 (latest)

weary windBOT
#

Hi @uneven grotto. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The <Picture /> component in Astro is designed to generate a <picture> element with multiple <source> elements, allowing you to display responsive images with multiple formats. However, it doesn't seem to support multiple image sizes directly. Instead, it generates different image formats from a single source image.

Here's an example of how to use the <Picture /> component:

import { Picture } from 'astro:assets';
import myImage from './my-image.jpg';

<Picture src={myImage} formats={['avif', 'webp']} alt="My super image in multiple formats!" />

This will generate the following HTML:

<picture>
 <source srcset="..." type="image/avif" />
 <source srcset="..." type="image/webp" />
 <img src="..." alt="My super image in multiple formats!" />
</picture>

The formats property is used to generate a <source> in each of the specified image formats. The browser will then determine the best image to display.

If you need to display different source images based on media queries, you might need to create a custom image component using the getImage() function. Here's an example of how to do this:

import type { ImageMetadata } from "astro";
import { getImage } from "astro:assets";

interface Props { 
  mobileImgUrl: string | ImageMetadata; 
  desktopImgUrl: string | ImageMetadata; 
  alt: string;
}

const { mobileImgUrl, desktopImgUrl, alt } = Astro.props;

const mobileImg = await getImage({ src: mobileImgUrl, format: "webp", width: 200, height: 200,});
const desktopImg = await getImage({ src: desktopImgUrl, format: "webp", width: 800, height: 200,});

This will allow you to define each of your responsive images by calling the getImage() function with your desired properties.

#

@uneven grotto kapa.ai is still learning and improving, please let us know how it did by reacting below