Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 158 additions & 17 deletions src/content/docs/en/guides/images.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ i18nReady: true
---
import Since from '~/components/Since.astro';
import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro';
import Badge from '~/components/Badge.astro';


Astro provides several ways for you to use images on your site, whether they are stored locally inside your project, linked to from an external URL, or managed in a CMS or CDN!
Expand Down Expand Up @@ -84,10 +85,6 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900
/>
```

Currently, the built-in assets feature does not include a `<Picture />` component.

Instead, you can [generate images or custom components using `getImage()`](#generating-images-with-getimage) that use the HTML image attributes `srcset` and `sizes` or the `<picture>` tag [for art direction or to create responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction).

#### Properties

##### src (required)
Expand Down Expand Up @@ -145,6 +142,76 @@ When using local images in their original aspect ratio, the `width` and `height`

However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files.

##### densities

<Since v="3.3.0" /> <Badge>Experimental</Badge>

A list of pixel densities to generate for the image.

If provided, this value will be used to generate a `srcset` attribute on the `<img>` tag. Do not provide a value for `widths` when using this value.

Densities that are equal to widths larger than the original image will be ignored to avoid upscaling the image.

```astro
---
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png";
---
<Image src={myImage} width={myImage.width / 2} densities={[1.5, 2]} alt="A description of my image." />
```

```html
<img
src="/_astro/my_image.hash.webp"
srcset="
/_astro/my_image.hash.webp 1.5x
/_astro/my_image.hash.webp 2x
"
alt="A description of my image."
width="800"
height="450"
loading="lazy"
decoding="async"
/>
```

##### widths

<Since v="3.3.0" /> <Badge>Experimental</Badge>

A list of widths to generate for the image.

If provided, this value will be used to generate a `srcset` attribute on the `<img>` tag. A [`sizes` property](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) must also be provided.

Do not provide a value for `densities` when using this value. Only one of these two values can be used to generate a `srcset`.

Widths that are larger than the original image will be ignored to avoid upscaling the image.

```astro
---
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---
<Image src={myImage} widths={[240, 540, 720, myImage.width]} alt="A description of my image." />
```

```html
<img
src="/_astro/my_image.hash.webp"
srcset="
/_astro/my_image.hash.webp 240w,
/_astro/my_image.hash.webp 540w,
/_astro/my_image.hash.webp 720w,
/_astro/my_image.hash.webp 1600w
"
alt="A description of my image."
width="1600"
height="900"
loading="lazy"
decoding="async"
/>
```

##### format

You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used.
Expand Down Expand Up @@ -209,6 +276,81 @@ const {src, ...attrs} = Astro.props;
</style>
```

### `<Picture />`

<Since v="3.3.0" /> <Badge>Experimental</Badge>

Use the built-in `<Picture />` Astro component to display a responsive image with multiple formats and/or sizes.

```astro title="src/pages/index.astro"
---
import { Picture } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---

<!-- `alt` is mandatory on the Picture component -->
<Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." />
```

```html
<!-- Output -->
<picture>
<source srcset="/_astro/my_image.hash.avif" type="image/avif" />
<source srcset="/_astro/my_image.hash.webp" type="image/webp" />
<img
src="/_astro/my_image.hash.jpg"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>
</picture>
```

#### Properties

`<Picture />` accepts all the properties of the `<Image />` component, plus the following:

##### `formats`

An array of image formats to use for the `<source>` tags. Entries will be added as `<source>` elements in the order they are listed, and this order determines which format is displayed. For the best performance, list the most modern format first (e.g. `webp` or `avif`). By default, this is set to `['webp']`.

##### `fallbackFormat`

Format to use as a fallback value for the `<img>` tag.

Defaults to `.png` for static images, `.gif` for animated images, and `.svg` for SVG files.

##### `pictureAttributes`

An object of attributes to be added to the `<picture>` tag.

Use this property to apply attributes to the outer `<picture>` element itself. Attributes applied to the `<Picture />` component directly will apply to the inner `<img>` element, except for those used for image transformation.

```astro
---
import { Picture } from "astro:assets";
import myImage from "../my_image.png"; // Image is 1600x900
---

<Picture src={myImage} alt="A description of my image." pictureAttributes={{style: "background-color: red;"}} />
```

```html
<picture style="background-color: red;">
<source srcset="/_astro/my_image.hash.webp" type="image/webp" />
<img
src="/_astro/my_image.hash.png"
alt="A description of my image."
width="1600"
height="900"
loading="lazy"
decoding="async"
/>
</picture>
```

### `<img>`

The [Astro template syntax](/en/core-concepts/astro-syntax/) also supports writing an `<img>` tag directly, with full control over its final output. These images will not be processed and optimized.
Expand Down Expand Up @@ -258,7 +400,7 @@ For remote images, use the image's **full URL** as the `src` value:

### Choosing `<Image />` vs `<img>`

The `<Image />` component optimizes your image and infers width and height (of local images) based on the original aspect ratio to avoid CLS. But, it only works with certain formats and does not provide a `<picture>` element, nor does it support `srcset`.
The `<Image />` component optimizes your image and infers width and height (of local images) based on the original aspect ratio to avoid CLS.

Use the HTML `<img>` element when you cannot use the `<Image />` component, for example:
- for unsupported image formats
Expand Down Expand Up @@ -484,8 +626,13 @@ It returns an object with the following properties:

```js
{
options: {...} // Original parameters passed
src: "https//..." // Path to the generated image
rawOptions: {...}, // Original parameters passed
options: {...}, // Validated parameters passed
src: "...", // Path to the generated image
srcSet: {
values: [...], // Generated values for srcset, every entry has a url and a size descriptor
attribute: "", // Generated srcset attribute from the values
}
attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..)
}
```
Expand Down Expand Up @@ -701,13 +848,7 @@ If you were using the image integration in Astro v2.x, complete the following st
/>
```

4. Remove any existing `<Picture />` components.

Currently, the built-in assets feature does not include a `<Picture />` component.

Instead, you can use the HTML image attributes `srcset` and `sizes` or the `<picture>` tag [for art direction or to create responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction).

5. Choose a default image service.
4. Choose a default image service.

[Sharp](https://github.com/lovell/sharp) is now the default image service used for `astro:assets`. If you would like to use Sharp, no configuration is required.

Expand All @@ -731,7 +872,7 @@ The new `image` helper for content collections lets you validate the image metad

### Navigating Image Imports in Astro v3.0

In Astro v3.0, if you have to preserve the old import behavior for images and require a string representation of the image's URL, append `?url` to the end of your image path when importing it. For example:
In Astro v3.0, if you have to preserve the old import behavior for images and require a string representation of the image's URL, append `?url` to the end of your image path when importing it. For example:

```astro title="src/pages/blog/MyImages.astro"
---
Expand All @@ -744,8 +885,8 @@ import Sprite from '../assets/logo.svg?url';

```

This approach ensures you obtain the URL string. Keep in mind that during development, Astro uses a `src/` path, but upon building, it generates hashed paths like `/_astro/cat.a6737dd3.png`.
This approach ensures you obtain the URL string. Keep in mind that during development, Astro uses a `src/` path, but upon building, it generates hashed paths like `/_astro/cat.a6737dd3.png`.

If you prefer to work directly with the image object itself, you can access the `.src` property. This approach is best for tasks like managing image dimensions for Core Web Vitals metrics and preventing CLS.
If you prefer to work directly with the image object itself, you can access the `.src` property. This approach is best for tasks like managing image dimensions for Core Web Vitals metrics and preventing CLS.

If you are transitioning into the new import behavior, combining `?url` and `.src` methods might be the right method for seamless image handling.
25 changes: 24 additions & 1 deletion src/content/docs/en/reference/image-service-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
title: Image Service API
i18nReady: true
---
import Badge from '~/components/Badge.astro';
import Since from '~/components/Since.astro';

`astro:assets` was designed to make it easy for any image optimization service to build a service on top of Astro.

Expand Down Expand Up @@ -173,6 +175,8 @@ export type ImageTransform = {
src: ImageMetadata | string;
width?: number;
height?: number;
widths?: number[] | undefined;
densities?: (number | `${number}x`)[] | undefined;
quality?: ImageQuality;
format?: OutputFormat;
alt?: string;
Expand Down Expand Up @@ -207,6 +211,25 @@ You must return a `format` to ensure that the proper MIME type is served to user

This hook returns all additional attributes used to render the image as HTML, based on the parameters passed by the user (`options`).

### `getSrcSet()`
<Since v="3.3.0" /> <Badge>Experimental</Badge>

**Optional for both local and external services.**

`getSrcSet?: (options: ImageTransform, imageConfig: AstroConfig['image']): SrcSetValue[] | Promise<SrcSetValue[]>;`

This hook generates multiple variants of the specified image, for example, to generate a `srcset` attribute on an `<img>` or `<picture>`'s `source`.

This hook returns an array of objects with the following properties:

```ts
export type SrcSetValue = {
transform: ImageTransform;
descriptor?: string;
attributes?: Record<string, any>;
};
```

### `validateOptions()`

**Optional for both local and external services**
Expand All @@ -215,7 +238,7 @@ This hook returns all additional attributes used to render the image as HTML, ba

This hook allows you to validate and augment the options passed by the user. This is useful for setting default options, or telling the user that a parameter is required.

[See how `validateOptions()` is used in Astro built-in services](https://github.com/withastro/astro/blob/af4bd5e79c0bd662d58aeb016a61950e176b0a26/packages/astro/src/assets/services/service.ts#L106).
[See how `validateOptions()` is used in Astro built-in services](https://github.com/withastro/astro/blob/0ab6bad7dffd413c975ab00e545f8bc150f6a92f/packages/astro/src/assets/services/service.ts#L124).

## User configuration

Expand Down