diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index 58ed5107a8a09..251cf3249509d 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -245,7 +245,7 @@ import myImage from '../assets/my_image.png'; // Image is 1600x900 /> ``` -The `` component accepts [several component properties](/en/reference/modules/astro-assets/#image-properties) as well as any attributes accepted by the HTML `` tag. +The `` component accepts [several component properties](/en/reference/modules/astro-assets/#image-) as well as any attributes accepted by the HTML `` tag. The following example provides a `class` to the image component which will apply to the final `` element. @@ -313,7 +313,7 @@ import myImage from '../assets/my_image.png'; // Image is 1600x900 ``` -See details about [the `` component properties](/en/reference/modules/astro-assets/#picture-properties) in the `astro:assets` reference. +See details about [the `` component properties](/en/reference/modules/astro-assets/#picture-) in the `astro:assets` reference. ### Responsive image behavior @@ -490,7 +490,7 @@ The [Astro template syntax](/en/reference/astro-syntax/) also supports writing a Local images must be imported from the relative path from the existing `.astro` file, or you can configure and use an [import alias](/en/guides/imports/#aliases). Then, you can access the image's `src` and other properties to use in the `` tag. -Imported image assets match the following signature: +Imported image assets match the [`ImageMetadata` type](/en/reference/modules/astro-assets/#imagemetadata-1) and have the following signature: ```ts interface ImageMetadata { diff --git a/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx b/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx index 0a35bf13c2977..3a114da94342a 100644 --- a/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx +++ b/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx @@ -333,7 +333,7 @@ import rocket from '../assets/rocket.png'; A rocketship in space. ``` -Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-properties) and note that several will differ from Gatsby's attributes. +Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-) and note that several will differ from Gatsby's attributes. To continue using [images in Markdown (`.md`) files](/en/guides/images/#images-in-markdown-files) using standard Markdown syntax (`![]()`), you may need to update the link. Using the HTML `` tag directly is not supported in `.md` files for local images, and must be converted to Markdown syntax. diff --git a/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx b/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx index e997018bbaed2..da253d01898ba 100644 --- a/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx +++ b/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx @@ -426,7 +426,7 @@ See more about [Styling in Astro](/en/guides/styling/). Convert any Next `` components to [Astro's own image component](/en/guides/images/) in `.astro` or `.mdx` files, or to a [standard HTML `` / JSX ``](/en/guides/images/#images-in-ui-framework-components) tag as appropriate in your React components. -Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-properties) and note that several will differ from Next's attributes. +Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-) and note that several will differ from Next's attributes. ```astro title="src/pages/index.astro" --- diff --git a/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx b/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx index f2c65d6118ace..935610c7c83c8 100644 --- a/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx +++ b/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx @@ -491,7 +491,7 @@ See more about [Styling in Astro](/en/guides/styling/). Convert any [Nuxt `` or `` components](https://image.nuxt.com/usage/nuxt-img) to [Astro's own image component](/en/guides/images/) in `.astro` or `.mdx` files, or to a [standard HTML ``](/en/guides/images/#images-in-ui-framework-components) or `` tag as appropriate in your Vue components. -Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-properties) and note that several will differ from Nuxt's attributes. +Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/reference/modules/astro-assets/#image-) and note that several will differ from Nuxt's attributes. ```astro title="src/pages/index.astro" --- diff --git a/src/content/docs/en/guides/upgrade-to/v3.mdx b/src/content/docs/en/guides/upgrade-to/v3.mdx index 7a8d27802f6e0..21b63c0ede519 100644 --- a/src/content/docs/en/guides/upgrade-to/v3.mdx +++ b/src/content/docs/en/guides/upgrade-to/v3.mdx @@ -829,7 +829,7 @@ If you were using the image integration in Astro v2.x, complete the following st Change all `import` statements from `@astrojs/image/components` to `astro:assets` in order to use the new built-in `` component. - Remove any component attributes that are not [currently supported image asset properties](/en/reference/modules/astro-assets/#image-properties). + Remove any component attributes that are not [currently supported image asset properties](/en/reference/modules/astro-assets/#image-). For example, `aspectRatio` is no longer supported, as it is now automatically inferred from the `width` and `height` attributes. diff --git a/src/content/docs/en/reference/image-service-reference.mdx b/src/content/docs/en/reference/image-service-reference.mdx index 81089315aefba..75fbbc0185555 100644 --- a/src/content/docs/en/reference/image-service-reference.mdx +++ b/src/content/docs/en/reference/image-service-reference.mdx @@ -129,7 +129,7 @@ In dev mode and when using an adapter to render on demand, Astro doesn't know ah #### getConfiguredImageService & imageConfig -If you implement your own endpoint as an Astro endpoint, you can use `getConfiguredImageService` and `imageConfig` to call your service's `parseURL` and `transform` methods and provide the image config. +If you implement your own endpoint as an Astro endpoint, you can use [`getConfiguredImageService`](/en/reference/modules/astro-assets/#getconfiguredimageservice) and [`imageConfig`](/en/reference/modules/astro-assets/#imageconfig) to call your service's `parseURL` and `transform` methods and provide the image config. To access the image service config ([`image.service.config`](/en/reference/configuration-reference/#imageservice)), you can use `imageConfig.service.config`. @@ -162,7 +162,7 @@ export const GET: APIRoute = async ({ request }) => {

-**Type:** `(options: ImageTransform, imageConfig: AstroConfig['image']) => string | Promise`
+**Type:** (options: ImageTransform, imageConfig: AstroConfig['image']) => string | Promise\

@@ -172,30 +172,13 @@ For local services, this hook returns the URL of the endpoint that generates you For external services, this hook returns the final URL of the image. -For both types of services, `options` are the properties passed by the user as attributes of the `` component or as options to `getImage()`. They are of the following type: - -```ts -export type ImageTransform = { - // ESM imported images | remote/public image paths - src: ImageMetadata | string; - width?: number | undefined; - height?: number | undefined; - widths?: number[] | undefined; - densities?: (number | `${number}x`)[] | undefined; - quality?: ImageQuality | undefined; - format?: OutputFormat | undefined; - fit?: ImageFit | undefined; - position?: string | undefined; - [key: string]: any; -}; -``` - +For both types of services, `options` are the properties passed by the user as attributes of the `` component or as options to `getImage()`. ### `parseURL()`

-**Type:** `(url: URL, imageConfig: AstroConfig['image']) => { src: string, [key: string]: any } | undefined | Promise<{ src: string, [key: string]: any }> | Promise`
+**Type:** (url: URL, imageConfig: AstroConfig['image']) => \{ src: string, [key: string]: any \} | undefined | Promise\<\{ src: string, [key: string]: any \}\> | Promise\

@@ -207,7 +190,7 @@ This hook parses the generated URLs by `getURL()` back into an object with the d

-**Type:** `(inputBuffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig: AstroConfig['image']) => Promise<{ data: Uint8Array; format: ImageOutputFormat }>`
+**Type:** (inputBuffer: Uint8Array, options: \{ src: string, [key: string]: any \}, imageConfig: AstroConfig['image']) => Promise\<\{ data: Uint8Array; format: ImageOutputFormat \}\>

@@ -221,7 +204,7 @@ You must return a `format` to ensure that the proper MIME type is served to user

-**Type:** `(options: ImageTransform, imageConfig: AstroConfig['image'] ) => Record | Promise>`
+**Type:** (options: ImageTransform, imageConfig: AstroConfig['image'] ) => Record\ | Promise\\>

@@ -233,7 +216,7 @@ This hook returns all additional attributes used to render the image as HTML, ba

-**Type:** `(options: ImageTransform, imageConfig: AstroConfig['image'] ) => UnresolvedSrcSetValue[] | Promise`
+**Type:** (options: ImageTransform, imageConfig: AstroConfig['image'] ) => UnresolvedSrcSetValue[] | Promise\

@@ -255,7 +238,7 @@ export type UnresolvedSrcSetValue = {

-**Type:** `(options: ImageTransform, imageConfig: AstroConfig['image'] ) => ImageTransform | Promise` +**Type:** (options: ImageTransform, imageConfig: AstroConfig['image'] ) => ImageTransform | Promise\

@@ -310,540 +293,3 @@ Then, users will be able to get autocomplete and type safety for your custom pro // ^^^^^^^^^^ // Type 'string' is not assignable to type 'number | undefined'. ``` - -## Utilities - -Astro exposes a number of helper functions that can be used to develop a custom image service. These utilities can be imported from `astro/assets/utils`: - -```ts -import { - isRemoteAllowed, - matchHostname, - matchPathname, - matchPattern, - matchPort, - matchProtocol, - isESMImportedImage, - isRemoteImage, - resolveSrc, - imageMetadata, - emitESMImage, - emitImageMetadata, - getOrigQueryParams, - inferRemoteSize, - propsToFilename, - hashTransform -} from "astro/assets/utils"; -``` - -### `isRemoteAllowed()` - -

-**Type:** `(src: string, { domains, remotePatterns }: { domains: string[], remotePatterns: RemotePattern[] }) => boolean`
- -

- -Determines whether a given remote resource, identified by its source URL, is allowed based on specified domains and remote patterns. - - -```ts -import { isRemoteAllowed } from 'astro/assets/utils'; - -const testImageURL = 'https://example.com/images/test.jpg'; -const domains = ['example.com', 'anotherdomain.com']; -const remotePatterns = [ - { protocol: 'https', hostname: 'images.example.com', pathname: '/**' }, // Allow any path under this hostname -]; - -const url = new URL(testImageURL); -const isAllowed = isRemoteAllowed(url.href, { domains, remotePatterns }); - -console.log(`Is the remote image allowed? ${isAllowed}`); -``` - -### `matchHostname()` - -

-**Type:** `(url: URL, hostname?: string, allowWildcard = false) => boolean`
- -

- -Matches a given URL's hostname against a specified hostname, with optional support for wildcard patterns. - -```ts -import { matchHostname } from 'astro/assets/utils'; - -const testURL = new URL('https://sub.example.com/path/to/resource'); - -// Example usage of matchHostname -const hostnameToMatch = 'example.com'; - -// Match without wildcard -const isMatchWithoutWildcard = matchHostname(testURL, hostnameToMatch); -console.log(`Does the hostname match without wildcard? ${isMatchWithoutWildcard}`); // Output: false - -// Match with wildcard -const isMatchWithWildcard = matchHostname(testURL, hostnameToMatch, true); -console.log(`Does the hostname match with wildcard? ${isMatchWithWildcard}`); // Output: true -``` - -### `matchPathname()` - -

-**Type:** `(url: URL, pathname?: string, allowWildcard = false) => boolean`
- -

- -Matches a given URL's pathname against a specified pattern, with optional support for wildcards. - -```ts -import { matchPathname } from 'astro/assets/utils'; - -const testURL = new URL('https://example.com/images/photo.jpg'); - -// Example pathname to match -const pathnameToMatch = '/images/photo.jpg'; - -// Match without wildcard -const isMatchWithoutWildcard = matchPathname(testURL, pathnameToMatch); -console.log(`Does the pathname match without wildcard? ${isMatchWithoutWildcard}`); // Output: true - -// Match with wildcard -const wildcardPathname = '/images/*'; -const isMatchWithWildcard = matchPathname(testURL, wildcardPathname, true); -console.log(`Does the pathname match with wildcard? ${isMatchWithWildcard}`); // Output: true -``` - -### `matchPattern()` - -

-**Type:** `(url: URL, remotePattern: RemotePattern) => boolean`
- -

- -Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. - -```ts -import { matchPattern } from 'astro/assets/utils'; - -const testURL = new URL('https://images.example.com/photos/test.jpg'); - -// Define a remote pattern to match the URL -const remotePattern = { - protocol: 'https', - hostname: 'images.example.com', - pathname: '/photos/**', // Wildcard to allow all files under /photos/ - port: '', // Optional: Match any port or leave empty for default -}; - -// Check if the URL matches the remote pattern -const isPatternMatched = matchPattern(testURL, remotePattern); - -console.log(`Does the URL match the remote pattern? ${isPatternMatched}`); // Output: true -``` - -### `matchPort()` - -

-**Type:** `(url: URL, port?: string) => boolean`
- -

- -Checks if the given URL's port matches the specified port. If no port is provided, it returns `true`. - -```ts -import { matchPort } from 'astro/assets/utils'; - -const testURL1 = new URL('https://example.com:8080/resource'); -const testURL2 = new URL('https://example.com/resource'); - -// Example usage of matchPort -const portToMatch = '8080'; - -// Match a URL with a port specified -const isPortMatch1 = matchPort(testURL1, portToMatch); -console.log(`Does the port match? ${isPortMatch1}`); // Output: true - -// Match a URL without a port specified (default port will be assumed) -const isPortMatch2 = matchPort(testURL2, portToMatch); -console.log(`Does the port match? ${isPortMatch2}`); // Output: false - -// Check a URL without explicitly providing a port (defaults to true if port is undefined) -const isPortMatch3 = matchPort(testURL1); -console.log(`Does the port match (no port specified)? ${isPortMatch3}`); // Output: true -``` - -### `matchProtocol()` - -

-**Type:** `(url: URL, protocol?: string) => boolean`
- -

- -Compares the protocol of the provided URL with a specified protocol. - -```ts -import { matchProtocol } from 'astro/assets/utils'; - -const testURL1 = new URL('https://example.com/resource'); -const testURL2 = new URL('http://example.com/resource'); - -// Example usage of matchProtocol -const protocolToMatch = 'https'; - -// Match a URL with correct protocol -const isProtocolMatch1 = matchProtocol(testURL1, protocolToMatch); -console.log(`Does the protocol match for testURL1? ${isProtocolMatch1}`); // Output: true - -// Match a URL with incorrect protocol -const isProtocolMatch2 = matchProtocol(testURL2, protocolToMatch); -console.log(`Does the protocol match for testURL2? ${isProtocolMatch2}`); // Output: false - -// Match a URL without explicitly providing a protocol (defaults to true if protocol is undefined) -const isProtocolMatch3 = matchProtocol(testURL1); -console.log(`Does the protocol match (no protocol specified)? ${isProtocolMatch3}`); // Output: true -``` - -### `isESMImportedImage()` - -

- **Type:** `(src: ImageMetadata | string) => boolean`
- -

- -Determines if the given source is an ECMAScript Module (ESM) imported image. - -```ts -import { isESMImportedImage } from 'astro/assets/utils'; - -// Example usage of isESMImportedImage -const imageMetadataExample = { - src: '/images/photo.jpg', - width: 800, - height: 600, - format: 'jpg', -}; - -const filePathExample = '/images/photo.jpg'; - -// Check if the input is an ESM imported image -const isMetadataImage = isESMImportedImage(imageMetadataExample); -console.log(`Is imageMetadataExample an ESM imported image? ${isMetadataImage}`); // Output: true - -const isFilePathImage = isESMImportedImage(filePathExample); -console.log(`Is filePathExample an ESM imported image? ${isFilePathImage}`); // Output: false -``` - - -### `isRemoteImage()` - -

- **Type:** `(src: ImageMetadata | string) => boolean`
- -

- -Determines if the provided source is a remote image URL in the form of a string. - - -```ts -import { isRemoteImage } from 'astro/assets/utils'; - -// Example usage of isRemoteImage -const remoteImageUrl = 'https://example.com/images/photo.jpg'; -const localImageMetadata = { - src: '/images/photo.jpg', - width: 800, - height: 600, - format: 'jpg', -}; - -// Check if the input is a remote image URL -const isRemote1 = isRemoteImage(remoteImageUrl); -console.log(`Is remoteImageUrl a remote image? ${isRemote1}`); // Output: true - -const isRemote2 = isRemoteImage(localImageMetadata); -console.log(`Is localImageMetadata a remote image? ${isRemote2}`); // Output: false -``` - -### `resolveSrc()` - -

- **Type:** `(src: UnresolvedImageTransform['src']) => Promise`
- -

- -Returns the image source. This function ensures that if `src` is a Promise (e.g., a dynamic `import()`), it is awaited and the correct `src` is extracted. If `src` is already a resolved value, it is returned as-is. - -```ts -import { resolveSrc } from 'astro/assets/utils'; -import localImage from "./images/photo.jpg"; - -const resolvedLocal = await resolveSrc(localImage); -// will be `{ src: '/images/photo.jpg', width: 800, height: 600, format: 'jpg' }` - -const resolvedRemote = await resolveSrc("https://example.com/remote-img.jpg"); -// will be `"https://example.com/remote-img.jpg"` - -const resolvedDynamic = await resolveSrc(import("./images/dynamic-image.jpg")) -// will be `{ src: '/images/dynamic-image.jpg', width: 800, height: 600, format: 'jpg' }` -``` - - -### `imageMetadata()` - -

- **Type:** `(data: Uint8Array, src?: string) => Promise>`
- -

- -Extracts image metadata such as dimensions, format, and orientation from the provided image data. - -```ts -import { imageMetadata } from 'astro/assets/utils'; - -async function extractImageMetadata() { - // Example image data (Uint8Array) - const exampleImageData = new Uint8Array([/* ...binary image data... */]); - - // Optional source path (useful for debugging or additional metadata context) - const sourcePath = '/images/photo.jpg'; - - try { - // Extract metadata from the image data - const metadata = await imageMetadata(exampleImageData, sourcePath); - - console.log('Extracted Image Metadata:', metadata); - // Example output: - // { - // width: 800, - // height: 600, - // format: 'jpg', - // orientation: undefined - // } - } catch (error) { - console.error('Failed to extract metadata from image:', error); - } -} - -await extractImageMetadata(); -``` - -### `emitESMImage()` - -:::caution[Deprecated] -Use the [`emitImageMetadata`](#emitimagemetadata) function instead. -::: - -

- **Type:** `(id: string | undefined, _watchMode: boolean, experimentalSvgEnabled: boolean, fileEmitter?: FileEmitter) => Promise`
- -

- - -Processes an image file and emits its metadata and optionally its contents. In build mode, the function uses `fileEmitter` to generate an asset reference. In development mode, it resolves to a local file URL with query parameters for metadata. - -```ts - -import { emitESMImage } from 'astro/assets/utils'; - -const imageId = '/images/photo.jpg'; -const unusedWatchMode = false; // Deprecated, unused -const unusedExperimentalSvgEnabled = false; // Set to `true` only if you are using SVG and want the file data to be embedded - -try { - const result = await emitESMImage(imageId, unusedWatchMode, unusedExperimentalSvgEnabled); - if (result) { - console.log('Image metadata with contents:', result); - // Example output: - // { - // width: 800, - // height: 600, - // format: 'jpg', - // contents: Uint8Array([...]) - // } - } else { - console.log('No metadata was emitted for this image.'); - } -} catch (error) { - console.error('Failed to emit ESM image:', error); -} - -``` - -### `emitImageMetadata()` - -

- **Type:** `(id: string | undefined, fileEmitter?: FileEmitter) => Promise`
- -

- - -Processes an image file and emits its metadata and optionally its contents. In build mode, the function uses `fileEmitter` to generate an asset reference. In development mode, it resolves to a local file URL with query parameters for metadata. - -```ts - -import { emitImageMetadata } from 'astro/assets/utils'; - -const imageId = '/images/photo.jpg'; - -try { - const result = await emitImageMetadata(imageId); - if (result) { - console.log('Image metadata with contents:', result); - // Example output: - // { - // width: 800, - // height: 600, - // format: 'jpg', - // contents: Uint8Array([...]) - // } - } else { - console.log('No metadata was emitted for this image.'); - } -} catch (error) { - console.error('Failed to emit ESM image:', error); -} - -``` - -### `getOrigQueryParams()` - -

- **Type:** `(params: URLSearchParams) => Pick | undefined`
- -

- - -Retrieves the `width`, `height`, and `format` of an image from a [`URLSearchParams` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). If any of these parameters are missing or invalid, the function returns `undefined`. - -```ts - -import { getOrigQueryParams } from 'astro/assets/utils'; - -const url = new URL('https://example.com/image.jpg?width=800&height=600&format=jpg'); -const queryParams = url.searchParams; - -// Extract the original query parameters -const origParams = getOrigQueryParams(queryParams); - -if (origParams) { - console.log('Original query parameters:', origParams); - // Example output: - // { - // width: 800, - // height: 600, - // format: 'jpg' - // } -} else { - console.log('Failed to extract original query parameters.'); -} -``` - -### `inferRemoteSize()` - -

- **Type:** `(url: string) => Promise>`
- -

- -Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata is available. - -```ts - -import { inferRemoteSize } from 'astro/assets/utils'; - -async function getRemoteImageSize() { - const remoteImageUrl = 'https://example.com/image.jpg'; - - try { - // Infer remote image size from the URL - const imageSize = await inferRemoteSize(remoteImageUrl); - - console.log('Inferred remote image size:', imageSize); - // Example output: - // { - // width: 1920, - // height: 1080, - // format: 'jpg' - // } - } catch (error) { - console.error('Failed to infer the size of the remote image:', error); - } -} - -await getRemoteImageSize(); -``` - -### `propsToFilename()` - -

- **Type:** `(filePath: string, transform: ImageTransform, hash: string) => string`
- -

- - -Generates a formatted filename for an image based on its source path, transformation properties, and a unique hash. - -The formatted filename follows this structure: - -`/_` - -- `prefixDirname`: If the image is an ESM imported image, this is the directory name of the original file path; otherwise, it will be an empty string. -- `baseFilename`: The base name of the file or a hashed short name if the file is a `data:` URI. -- `hash`: A unique hash string generated to distinguish the transformed file. -- `outputExtension`: The desired output file extension derived from the `transform.format` or the original file extension. - -```ts -import { propsToFilename } from 'astro/assets/utils'; - -function generateTransformedFilename() { - const filePath = '/images/photo.jpg'; - const transform = { - format: 'png', - src: '/images/photo.jpg' - }; - const hash = 'abcd1234'; - - // Generate the transformed filename based on the file path, transformation, and hash - const filename = propsToFilename(filePath, transform, hash); - - console.log('Generated transformed filename:', filename); - // Example output: '/images/photo_abcd1234.png' -} - -generateTransformedFilename(); -``` - -### `hashTransform()` - -

- **Type:** `(transform: ImageTransform, imageService: string, propertiesToHash: string[]) => string`
- -

- -Transforms the provided `transform` object into a hash string based on selected properties and the specified `imageService`. - -```ts - -import { hashTransform } from 'astro/assets/utils'; - -function generateTransformHash() { - const transform = { - src: '/images/photo.jpg', - width: 800, - height: 600, - format: 'jpg', - }; - - const imageService = 'astroImageService'; - const propertiesToHash = ['width', 'height', 'format']; - - // Generate the hash based on the transform, image service, and properties - const hash = hashTransform(transform, imageService, propertiesToHash); - - console.log('Generated transform hash:', hash); - // Example output: 'd41d8cd98f00b204e9800998ecf8427e' -} - -generateTransformHash(); -``` diff --git a/src/content/docs/en/reference/modules/astro-assets.mdx b/src/content/docs/en/reference/modules/astro-assets.mdx index 376e3964171a9..c7176b70b1de5 100644 --- a/src/content/docs/en/reference/modules/astro-assets.mdx +++ b/src/content/docs/en/reference/modules/astro-assets.mdx @@ -5,7 +5,7 @@ sidebar: i18nReady: true tableOfContents: minHeadingLevel: 2 - maxHeadingLevel: 6 + maxHeadingLevel: 3 --- import Since from '~/components/Since.astro'; import ReadMore from '~/components/ReadMore.astro'; @@ -16,13 +16,17 @@ Astro provides built-in components and helper functions for optimizing and displ ## Imports from `astro:assets` +The following helpers are imported from the virtual assets module: + ```js import { Image, Picture, getImage, inferRemoteSize, - } from 'astro:assets'; + getConfiguredImageService, + imageConfig, +} from 'astro:assets'; ``` ### `` @@ -55,15 +59,13 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 /> ``` -#### Image properties - The `` component accepts the following listed properties and [responsive image properties](#responsive-image-properties) in addition to all properties accepted by the HTML `` tag. -##### src (required) +#### `src` (required)

-**Type:** `ImageMetadata | string | Promise<{ default: ImageMetadata }>` +**Type:** ImageMetadata | string | Promise\<\{ default: ImageMetadata \}\>

The format of the `src` value of your image file depends on where your image file is located: @@ -106,7 +108,7 @@ The format of the `src` value of your image file depends on where your image fil /> ``` -##### alt (required) +#### `alt` (required)

@@ -117,11 +119,11 @@ Use the required `alt` attribute to provide a string of [descriptive alt text](h If an image is merely decorative (i.e. doesn't contribute to the understanding of the page), set `alt=""` so that screen readers and other assistive technologies know to ignore the image. -##### width and height (required for images in `public/`) +#### `width` and `height` (required for images in `public/`)

-**Type:** `number | undefined` +**Type:** ``number | `${number}` | undefined``

These properties define the dimensions to use for the image. @@ -132,7 +134,7 @@ When using images in their original aspect ratio, `width` and `height` are optio However, both of these properties are required for images stored in your `public/` folder as Astro is unable to analyze these files. -##### densities +#### `densities`

@@ -177,7 +179,7 @@ import myImage from '../assets/my_image.png'; /> ``` -##### widths +#### `widths`

@@ -195,7 +197,7 @@ Do not provide a value for `densities` when using this value. Only one of these Widths that are larger than the original image will be ignored to avoid upscaling the image. -```astro +```astro title="src/components/MyComponent.astro" --- import { Image } from 'astro:assets'; import myImage from '../assets/my_image.png'; // Image is 1600x900 @@ -232,7 +234,7 @@ import myImage from '../assets/my_image.png'; // Image is 1600x900 /> ``` -##### sizes +#### `sizes`

@@ -247,29 +249,29 @@ The `widths` and `sizes` attributes will be automatically generated for responsi The generated `sizes` attribute for `constrained` and `full-width` images is based on the assumption that the image is displayed close to the full width of the screen when the viewport is smaller than the image's width. If it is significantly different (e.g. if it's in a multi-column layout on small screens), you may need to adjust the `sizes` attribute manually for best results. -##### format +#### `format`

-**Type:** `ImageOutputFormat | undefined` +**Type:** ImageOutputFormat | undefined

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. By default, the `` component will produce a `.webp` file. -##### quality +#### `quality`

-**Type:** `ImageQuality | undefined` +**Type:** ImageQuality | undefined

`quality` is an optional property that can either be: - a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. - a number from `0` to `100` (interpreted differently between formats). -##### inferSize +#### `inferSize`

@@ -293,7 +295,7 @@ import { Image } from 'astro:assets'; `inferSize` can fetch the dimensions of a [remote image from a domain that has not been authorized](/en/guides/images/#authorizing-remote-images), however the image itself will remain unprocessed. -##### priority +#### `priority`

@@ -356,29 +358,27 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 ``` -#### Picture properties +`` accepts all the properties of [the `` component](#image-), including [responsive image properties](#responsive-image-properties), plus the following: -`` accepts all the properties of [the `` component](#image-properties), including [responsive image properties](#responsive-image-properties), plus the following: - -##### `formats` +#### `formats`

-**Type:** `ImageOutputFormat[]` +**Type:** ImageOutputFormat[]

An array of image formats to use for the `` tags. Entries will be added as `` 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` +#### `fallbackFormat`

-**Type:** `ImageOutputFormat` +**Type:** [`ImageOutputFormat`](#imageoutputformat)

Format to use as a fallback value for the `` tag. Defaults to `.png` for static images (or `.jpg` if the image is a JPG), `.gif` for animated images, and `.svg` for SVG files. -##### `pictureAttributes` +#### `pictureAttributes`

@@ -421,7 +421,7 @@ import myImage from "../my_image.png"; // Image is 1600x900 Setting the [`layout`](#layout) property on an [``](#image-) or [``](#picture-) component creates a responsive image and enables additional property settings. -```astro title=MyComponent.astro +```astro title="src/components/MyComponent.astro" --- import { Image } from 'astro:assets'; import myImage from '../assets/my_image.png'; @@ -470,7 +470,7 @@ The value for `layout` also defines the default styles applied to the `` ta You can override the default `object-fit` and `object-position` styles by setting the [`fit`](#fit) and [`position`](#position) props on the `` or `` component. -##### layout +##### `layout`

@@ -509,7 +509,7 @@ import myImage from '../assets/my_image.png'; This will disable responsive images ``` -##### fit +##### `fit`

@@ -522,7 +522,7 @@ Enabled when the [`layout`](#layout) property is set or configured. Defines how Values match those of CSS `object-fit`. Defaults to `cover`, or the value of [`image.objectFit`](/en/reference/configuration-reference/#imageobjectfit) if set. Can be used to override the default `object-fit` styles. -##### position +##### `position`

@@ -539,7 +539,7 @@ Values match those of CSS `object-position`. Defaults to `center`, or the value

-**Type:** `(options: UnresolvedImageTransform) => Promise` +**Type:** (options: UnresolvedImageTransform) => Promise\<GetImageResult\>

:::caution @@ -548,9 +548,11 @@ Values match those of CSS `object-position`. Defaults to `center`, or the value The `getImage()` function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an [API Route](/en/guides/endpoints/#server-endpoints-api-routes). It also allows you to create your own custom `` component. -`getImage()` takes an options object with the [same properties as the Image component](#image-properties) (except `alt`). +This takes an options object with the [same properties as the Image component](#image-) (except `alt`) and returns a [`GetImageResult` object](#getimageresult). -```astro +The following example generates an AVIF `background-image` for a `
`: + +```astro title="src/components/Background.astro" --- import { getImage } from "astro:assets"; import myBackground from "../background.png" @@ -558,41 +560,947 @@ import myBackground from "../background.png" const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) --- -
+
+``` + +### `inferRemoteSize()` + +

+ +**Type:** (url: string) => Promise\ImageMetadata, 'src' | 'fsPath'\>\>
+ +

+ +A function to set the original `width` and `height` of a remote image automatically. This can be used as an alternative to passing the [`inferSize` ](#infersize) property. + +```ts +import { inferRemoteSize } from 'astro:assets'; +const { width, height } = await inferRemoteSize("https://example.com/cat.png"); ``` -It returns an object with the following type: +### `getConfiguredImageService()` + +

+ +**Type:** () => Promise\<ImageService\>
+ +

+ +Retrieves the resolved [image service](/en/reference/configuration-reference/#imageservice). + +### `imageConfig` + +

+ +**Type:** [`AstroConfig["image"]`](/en/reference/configuration-reference/#image-options)
+ +

+ +The [configuration options for images](/en/reference/configuration-reference/#image-options) set by the user and merged with all defaults. + +## `astro:assets` types + +The following types are imported from the virtual assets module: ```ts -type GetImageResult = { - /* Additional HTML attributes needed to render the image (width, height, style, etc..) */ - attributes: Record; - /* Validated parameters passed */ - options: ImageTransform; - /* Original parameters passed */ - rawOptions: ImageTransform; - /* Path to the generated image */ - src: string; - srcSet: { - /* Generated values for srcset, every entry has a url and a size descriptor */ - values: SrcSetValue[]; - /* A value ready to use in`srcset` attribute */ - attribute: string; - }; +import type { + LocalImageProps, + RemoteImageProps, +} from "astro/assets"; +``` + +### `LocalImageProps` + +

+ +**Type:** ImageSharedProps\ & \{ src: ImageMetadata | Promise\<\{ default: ImageMetadata; \}\> } +

+ +Describes the [properties of a local image](#image-). This ensures that [`src`](#src-required) matches the shape of an imported image. + +Learn more about [imported images in `src/`](/en/guides/images/#images-in-src) with an example usage. + +### `RemoteImageProps` + +

+ +**Types:** +* `ImageSharedProps & { src: string; inferSize: true; }` +* `ImageSharedProps & { src: string; inferSize?: false | undefined; }` +

+ +Describes the [properties of a remote image](#image-). This ensures that when [`inferSize`](#infersize) is not provided or is set to `false`, both [`width` and `height`](#width-and-height-required-for-images-in-public) are required. + +## Imports from `astro/assets` + +The following helpers are imported from the regular assets module: + +```ts +import { + baseService, + getConfiguredImageService, + getImage, + isLocalService, +} from "astro/assets"; +``` + +### `baseService` + +

+ +**Type:** Omit\<LocalImageService, 'transform'\> +

+ +The built-in local image service which can be extended to [create a custom image service](/en/reference/image-service-reference/). + +The following example reuses the `baseService` to create a new image service: + +```ts title="src/image-service.ts" +import { baseService } from "astro/assets"; + +const newImageService = { + getURL: baseService.getURL, + parseURL: baseService.parseURL, + getHTMLAttributes: baseService.getHTMLAttributes, + async transform(inputBuffer, transformOptions) {...} } ``` -### inferRemoteSize() +### `getConfiguredImageService()` + +See [`getConfiguredImageService()`](#getconfiguredimageservice) from `astro:assets`. + +### `getImage()`

-**Type:** `(url: string) => Promise>`
- +**Type:** (options: UnresolvedImageTransform, imageConfig: AstroConfig['image']) => Promise\<GetImageResult\> +

+ +A function similar to [`getImage()`](#getimage) from `astro:assets` with two required arguments: an `options` object with [the same properties as the Image component](#image-) and a second object for the [image configuration](/en/reference/configuration-reference/#image-options). + +### `isLocalService()` + +

+ +**Type:** (service: ImageService | undefined) => boolean

-A function to infer the dimensions of remote images. This can be used as an alternative to passing the `inferSize` property. +Checks the type of an image service and returns `true` when this is a [local service](#localimageservice). + +## `astro/assets` types + +The following types are imported from the regular assets module: ```ts -import { inferRemoteSize } from 'astro:assets'; -const {width, height} = await inferRemoteSize("https://example.com/cat.png"); +import type { + LocalImageProps, + RemoteImageProps, +} from "astro/assets"; +``` + +### `LocalImageProps` + +See [`LocalImageProps`](#localimageprops) from `astro:assets`. + +### `RemoteImageProps` + +See [`RemoteImageProps`](#remoteimageprops) from `astro:assets`. + +## Imports from `astro/assets/utils` + +The following helpers are imported from the `utils` directory in the regular assets module and can be used to [build an image service](/en/reference/image-service-reference/): + +```ts +import { + isRemoteAllowed, + matchHostname, + matchPathname, + matchPattern, + matchPort, + matchProtocol, + isESMImportedImage, + isRemoteImage, + resolveSrc, + imageMetadata, + emitImageMetadata, + getOrigQueryParams, + inferRemoteSize, + propsToFilename, + hashTransform, + /* The following are deprecated: */ + emitESMImage, +} from "astro/assets/utils"; +``` + +### `isRemoteAllowed()` + +

+ +**Type:** (src: string, \{ domains, remotePatterns \}: \{ domains: string[], remotePatterns: RemotePattern[] \}) => boolean
+ +

+ +Determines whether a given remote resource, identified by its source URL, is allowed based on specified domains and remote patterns. + + +```ts +import { isRemoteAllowed } from 'astro/assets/utils'; + +const url = new URL('https://example.com/images/test.jpg'); +const domains = ['example.com', 'anotherdomain.com']; +const remotePatterns = [ + { + protocol: 'https', + hostname: 'images.example.com', + pathname: '/**', // Allow any path under this hostname + } +]; + +isRemoteAllowed(url.href, { domains, remotePatterns }); // Output: `true` +``` + +### `matchHostname()` + +

+ +**Type:** `(url: URL, hostname?: string, allowWildcard = false) => boolean`
+ +

+ +Matches a given URL's hostname against a specified hostname, with optional support for wildcard patterns. + +```ts +import { matchHostname } from 'astro/assets/utils'; + +const url = new URL('https://sub.example.com/path/to/resource'); + +matchHostname(url, 'example.com'); // Output: `false` +matchHostname(url, 'example.com', true); // Output: `true` +``` + +### `matchPathname()` + +

+ +**Type:** `(url: URL, pathname?: string, allowWildcard = false) => boolean`
+ +

+ +Matches a given URL's pathname against a specified pattern, with optional support for wildcards. + +```ts +import { matchPathname } from 'astro/assets/utils'; + +const testURL = new URL('https://example.com/images/photo.jpg'); + +matchPathname(testURL, '/images/photo.jpg'); // Output: `true` +matchPathname(testURL, '/images/'); // Output: `false` +matchPathname(testURL, '/images/*', true); // Output: `true` +``` + +### `matchPattern()` + +

+ +**Type:** (url: URL, remotePattern: RemotePattern) => boolean
+ +

+ +Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. + +```ts +import { matchPattern } from 'astro/assets/utils'; + +const url = new URL('https://images.example.com/photos/test.jpg'); +const remotePattern = { + protocol: 'https', + hostname: 'images.example.com', + pathname: '/photos/**', // Allow all files under /photos/ +}; + +matchPattern(url, remotePattern); // Output: `true` +``` + +### `matchPort()` + +

+ +**Type:** `(url: URL, port?: string) => boolean`
+**Default:** `true`
+ +

+ +Checks if the given URL's port matches the specified port. If no port is provided, it returns `true`. + +```ts +import { matchPort } from 'astro/assets/utils'; + +const urlWithPort = new URL('https://example.com:8080/resource'); +const urlWithoutPort = new URL('https://example.com/resource'); + +matchPort(urlWithPort, '8080'); // Output: `true` +matchPort(urlWithoutPort, '8080'); // Output: `false` +``` + +### `matchProtocol()` + +

+ +**Type:** `(url: URL, protocol?: string) => boolean`
+**Default:** `true`
+ +

+ +Compares the protocol of the provided URL with a specified protocol. This returns `true` if the protocol matches or if no protocol is provided. + +```ts +import { matchProtocol } from 'astro/assets/utils'; + +const secureUrl = new URL('https://example.com/resource'); +const regularUrl = new URL('http://example.com/resource'); + +matchProtocol(secureUrl, 'https'); // Output: `true` +matchProtocol(regularUrl, 'https'); // Output: `false` +``` + +### `isESMImportedImage()` + +

+ +**Type:** (src: ImageMetadata | string) => boolean
+ +

+ +Determines if the given source is an ECMAScript Module (ESM) imported image. + +```ts +import { isESMImportedImage } from 'astro/assets/utils'; + +const imageMetadata = { + src: '/images/photo.jpg', + width: 800, + height: 600, + format: 'jpg', +}; +const filePath = '/images/photo.jpg'; + +isESMImportedImage(imageMetadata); // Output: `true` +isESMImportedImage(filePath); // Output: `false` +``` + +### `isRemoteImage()` + +

+ +**Type:** (src: ImageMetadata | string) => boolean
+ +

+ +Determines if the provided source is a remote image URL in the form of a string. + +```ts +import { isRemoteImage } from 'astro/assets/utils'; + +const imageUrl = 'https://example.com/images/photo.jpg'; +const localImage = { + src: '/images/photo.jpg', + width: 800, + height: 600, + format: 'jpg', +}; + +isRemoteImage(imageUrl); // Output: `true` +isRemoteImage(localImage); // Output: `false` +``` + +### `resolveSrc()` + +

+ +**Type:** (src: UnresolvedImageTransform['src']) => Promise\ImageMetadata\>
+ +

+ +Returns the image source. This function ensures that if `src` is a Promise (e.g., a dynamic `import()`), it is awaited and the correct `src` is extracted. If `src` is already a resolved value, it is returned as-is. + +```ts +import { resolveSrc } from 'astro/assets/utils'; +import localImage from "./images/photo.jpg"; + +const resolvedLocal = await resolveSrc(localImage); +// Example value: `{ src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg', width: 800, height: 600, format: 'jpg' }` + +const resolvedRemote = await resolveSrc("https://example.com/remote-img.jpg"); +// Value: `"https://example.com/remote-img.jpg"` + +const resolvedDynamic = await resolveSrc(import("./images/dynamic-image.jpg")) +// Example value: `{ src: '/@fs/home/username/dev/astro-project/src/images/dynamic-image.jpg', width: 800, height: 600, format: 'jpg' }` +``` + +### `imageMetadata()` + +

+ +**Type:** (data: Uint8Array, src?: string) => Promise\ImageMetadata, 'src' | 'fsPath'\>\>
+ +

+ +Extracts image metadata such as dimensions, format, and orientation from the provided image data. + +```ts +import { imageMetadata } from 'astro/assets/utils'; + +const binaryImage = new Uint8Array([/* ...binary image data... */]); +const sourcePath = '/images/photo.jpg'; + +const metadata = await imageMetadata(binaryImage, sourcePath); +// Example value: +// { +// width: 800, +// height: 600, +// format: 'jpg', +// orientation: undefined +// } +``` + +### `emitImageMetadata()` + +

+ +**Type:** (id: string | undefined, fileEmitter?: Rollup.EmitFile) => Promise\<(ImageMetadata & \{ contents?: Buffer \}) | undefined\>
+ +

+ +Processes an image file and emits its metadata and optionally its contents. In build mode, the function uses `fileEmitter` to generate an asset reference. In development mode, it resolves to a local file URL with query parameters for metadata. + +```ts +import { emitImageMetadata } from 'astro/assets/utils'; + +const imageId = '/images/photo.jpg'; +const metadata = await emitImageMetadata(imageId); +// Example value: +// { +// src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg?origWidth=800&origHeight=600&origFormat=jpg', +// width: 800, +// height: 600, +// format: 'jpg', +// contents: Uint8Array([...]) +// } +``` + +### `getOrigQueryParams()` + +

+ +**Type:** (params: URLSearchParams) => Pick\<ImageMetadata, 'width' | 'height' | 'format'\> | undefined
+ +

+ +Retrieves the `width`, `height`, and `format` of an image from a [`URLSearchParams` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). If any of these parameters are missing or invalid, the function returns `undefined`. + +```ts +import { getOrigQueryParams } from 'astro/assets/utils'; + +const url = new URL('https://example.com/image.jpg?width=800&height=600&format=jpg'); +const origParams = getOrigQueryParams(url.searchParams); +// Example value: +// { +// width: 800, +// height: 600, +// format: 'jpg' +// } +``` + +### `inferRemoteSize()` + +

+ +**Type:** (url: string) => Promise\ImageMetadata, 'src' | 'fsPath'\>\>
+ +

+ +Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata is available. + +```ts +import { inferRemoteSize } from 'astro/assets/utils'; + +const remoteImageUrl = 'https://example.com/image.jpg'; +const imageSize = await inferRemoteSize(remoteImageUrl); +// Example value: +// { +// width: 1920, +// height: 1080, +// format: 'jpg' +// } +``` + +### `propsToFilename()` + +

+ +**Type:** (filePath: string, transform: ImageTransform, hash: string) => string
+ +

+ +Generates a formatted filename for an image based on its source path, transformation properties, and a unique hash. + +The formatted filename follows this structure: + +`/_` + +- `prefixDirname`: If the image is an ESM imported image, this is the directory name of the original file path; otherwise, it will be an empty string. +- `baseFilename`: The base name of the file or a hashed short name if the file is a `data:` URI. +- `hash`: A unique hash string generated to distinguish the transformed file. +- `outputExtension`: The desired output file extension derived from the `transform.format` or the original file extension. + +```ts +import { propsToFilename } from 'astro/assets/utils'; + +const filePath = '/images/photo.jpg'; +const transform = { format: 'png', src: filePath }; +const hash = 'abcd1234'; + +const filename = propsToFilename(filePath, transform, hash); +// Example value: '/images/photo_abcd1234.png' +``` + +### `hashTransform()` + +

+ +**Type:** (transform: ImageTransform, imageService: string, propertiesToHash: string[]) => string
+ +

+ +Transforms the provided `transform` object into a hash string based on selected properties and the specified `imageService`. + +```ts +import { hashTransform } from 'astro/assets/utils'; + +const transform = { + src: '/images/photo.jpg', + width: 800, + height: 600, + format: 'jpg', +}; +const imageService = 'astro/assets/services/sharp'; +const propertiesToHash = ['width', 'height', 'format']; + +const hash = hashTransform(transform, imageService, propertiesToHash); +// Example value: 'd41d8cd98f00b204e9800998ecf8427e' +``` + +### `emitESMImage()` + +:::caution[Deprecated] +Use the [`emitImageMetadata`](#emitimagemetadata) function instead. +::: + +

+ +**Type:** (id: string | undefined, _watchMode: boolean, experimentalSvgEnabled: boolean, fileEmitter?: Rollup.EmitFile) => Promise\<(ImageMetadata & \{ contents?: Buffer \}) | undefined\>
+ +

+ + +Processes an image file and emits its metadata and optionally its contents. In build mode, the function uses `fileEmitter` to generate an asset reference. In development mode, it resolves to a local file URL with query parameters for metadata. + +```ts +import { emitESMImage } from 'astro/assets/utils'; + +const imageId = '/images/photo.jpg'; +const unusedWatchMode = false; // Deprecated, unused +const unusedExperimentalSvgEnabled = false; // Set to `true` only if you are using SVG and want the file data to be embedded +const image = await emitESMImage(imageId, unusedWatchMode, unusedExperimentalSvgEnabled); +// Example value: +// { +// src: '/@fs/home/username/dev/astro-project/src/images/photo.jpg?origWidth=800&origHeight=600&origFormat=jpg', +// width: 800, +// height: 600, +// format: 'jpg', +// contents: Uint8Array([...]) +// } +``` + +## `astro` types + +```ts +import type { + GetImageResult, + ImageTransform, + UnresolvedImageTransform, + ImageMetadata, + ImageInputFormat, + ImageOutputFormat, + ImageQuality, + ImageQualityPreset, + RemotePattern, + ImageService, + ExternalImageService, + LocalImageService, + ImageServiceConfig, +} from "astro"; ``` + +### `GetImageResult` + +

+ +**Type:** `object`
+ +

+ +Describes the result of the transformation after the call to [`getImage()`](/en/reference/modules/astro-assets/#getimage). + +#### `attributes` + +

+ +**Type:** `Record` +

+ +Defines the additional HTML attributes needed to render the image (e.g. width, height, style). + +#### `options` + +

+ +**Type:** [`ImageTransform`](#imagetransform) +

+ +Describes the transformation settings after validation. + +#### `rawOptions` + +

+ +**Type:** [`ImageTransform`](#imagetransform) +

+ +Describes the original transformation settings. + +#### `src` + +

+ +**Type:** `string` +

+ +The path to the generated image. + +#### `srcSet` + +

+ +**Type:** \{ values: \{ transform: ImageTransform; descriptor?: string; attributes?: Record\; url: string; \}[]; attribute: string; \}
+ +

+ +An object describing how to render the [`srcset` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/img#srcset). + +##### `values` + +

+ +**Type:** \{ transform: ImageTransform; descriptor?: string; attributes?: Record\; url: string; \}[] +

+ +An array of generated values where each entry includes a URL and a size descriptor. This can be used to manually generate the value of the `srcset` attribute. + +##### `attribute` + +

+ +**Type:** `string` +

+ +A value ready to use in the `srcset` attribute. + +### `ImageTransform` + +

+ +**Type:** `object` +

+ +Defines the options accepted by the image transformation service. This contains a required `src` property, optional predefined properties, and any additional properties required by the image service: + +#### `src` + +

+ +**Type:** ImageMetadata | string +

+ +Defines the path to a local image in the `public` directory, the URL of a remote image, or the data from an imported image. + +#### `width` + +

+ +**Type:** `number | undefined` +

+ +The width of the image. + +#### `height` + +

+ +**Type:** `number | undefined` +

+ +The height of the image. + +#### `widths` + +

+ +**Type:** `number[] | undefined`
+ +

+ +A list of widths to generate for the image. + +#### `densities` + +

+ +**Type:** ``(number | `${number}x`)[] | undefined``
+ +

+ +A list of pixel densities to generate for the image. + +#### `quality` + +

+ +**Type:** ImageQuality | undefined +

+ +The desired quality for the output image. + +#### `format` + +

+ +**Type:** ImageOutputFormat | undefined +

+ +The desired format for the output image. + +#### `fit` + +

+ +**Type:** `'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | string | undefined`
+ +

+ +Defines a list of allowed values for the `object-fit` CSS property, extensible with any string. + +#### `position` + +

+ +**Type:** `string | undefined`
+ +

+ +Controls the value for the `object-position` CSS property. + +### `UnresolvedImageTransform` + +

+ +**Type:** Omit\<ImageTransform, "src"\> & \{ src: ImageMetadata | string | Promise\<\{ default: ImageMetadata \}\>; inferSize?: boolean; \} +

+ +Represents an image with transformation options. This contains the same properties as the [`ImageTransform` type](#imagetransform) with a different `src` type and an additional `inferSize` property. + +#### `src` + +

+ +**Type:** ImageMetadata | string | Promise\<\{ default: ImageMetadata \}\> +

+ +The path to an image imported or located in the `public` directory, or the URL of a remote image. + +#### `inferSize` + +

+ +**Type:** `boolean` +

+ +Determines whether the width and height of the image should be inferred. + +See also the [`inferSize` attribute](/en/reference/modules/astro-assets/#infersize) available on ``. + +### `ImageMetadata` + +

+ +**Type:** \{ src: string; width: number; height: number; format: ImageInputFormat; orientation?: number; \}
+ +

+ +Describes the data collected during image import. This contains the following properties: + +#### `src` + +

+ +**Type:** `string` +

+ +The absolute path of the image on the filesystem. + +#### `width` + +

+ +**Type:** `number` +

+ +The width of the image. + +#### `height` + +

+ +**Type:** `number` +

+ +The height of the image. + +#### `format` + +

+ +**Type:** [`ImageInputFormat`](#imageinputformat) +

+ +The format of the image. + +#### `orientation` + +

+ +**Type:** `number`
+ +

+ +The image orientation when its metadata contains this information. + +### `ImageInputFormat` + +

+ +**Type:** `"jpeg" | "jpg" | "png" | "tiff" | "webp" | "gif" | "svg" | "avif"`
+ +

+ +Describes a union of supported formats for imported images. + +### `ImageOutputFormat` + +

+ +**Type:** `string | "jpeg" | "jpg" | "png" | "webp" | "svg" | "avif"`
+ +

+ +Specifies the format for output images. This can be a predefined literal or any string. + +### `ImageQuality` + +

+ +**Type:** ImageQualityPreset | number
+ +

+ +Represents the perceptual quality of the output image as a union of predefined literals, a string, or a number. + +### `ImageQualityPreset` + +

+ +**Type:** `string | "low" | "mid" | "high" | "max"`
+ +

+ +Defines the available presets to control image quality, extensible with any string. + +### `RemotePattern` + +

+ +**Type:** `{ hostname?: string; pathname?: string; protocol?: string; port?: string; }`
+ +

+ +Describes a remote host through four optional properties: `hostname`, `pathname`, `protocol`, and `port`. + +### `ImageService` + +

+ +**Type:** ExternalImageService | LocalImageService +

+ +Defines the hooks that a local or external image service must provide. + +### `ExternalImageService` + +

+ +**Type:** `object` +

+ +Defines the hooks that an external image transformation service must provide. This requires a [`getUrl()` hook](/en/reference/image-service-reference/#geturl) and supports [three additional hooks](/en/reference/image-service-reference/#hooks). + +Learn how to build [external services](/en/reference/image-service-reference/#external-services) in the Image Service API reference with example usage. + +### `LocalImageService` + +

+ +**Type:** `object` +

+ +Defines the hooks that a local image transformation service must provide. This requires [`getUrl()`](/en/reference/image-service-reference/#geturl), [`parseUrl()`](/en/reference/image-service-reference/#parseurl), and [`transform()`](/en/reference/image-service-reference/#transform) hooks, and supports [additional hooks](/en/reference/image-service-reference/#hooks). + +Learn how to build [local services](/en/reference/image-service-reference/#local-services) in the Image Service API reference with example usage. + +### `ImageServiceConfig` + +

+ +**Type:** `{ entrypoint: 'astro/assets/services/sharp' | string; config?: T; }`
+ +

+ +Describes the configuration object for an image service. This contains the following properties: + +#### `entrypoint` + +

+ +**Type:** `'astro/assets/services/sharp' | string` +

+ +A package or path to the image service module. This can be Astro's built-in Sharp service or a third-party service. + +#### `config` + +

+ +**Type:** `Record` +

+ +A configuration object passed to the image service. The shape depends on the specific service being used. diff --git a/src/content/docs/ru/guides/upgrade-to/v3.mdx b/src/content/docs/ru/guides/upgrade-to/v3.mdx index c088577a271c3..b5c295a78075f 100644 --- a/src/content/docs/ru/guides/upgrade-to/v3.mdx +++ b/src/content/docs/ru/guides/upgrade-to/v3.mdx @@ -829,7 +829,7 @@ import rocket from '../images/rocket.svg'; Измените все `import`-операторы с `@astrojs/image/components` на `astro:assets`, чтобы использовать новый встроенный компонент ``. - Удалите все атрибуты компонента, которые не являются [поддерживаемыми свойствами изображений](/ru/reference/modules/astro-assets/#image-properties). + Удалите все атрибуты компонента, которые не являются [поддерживаемыми свойствами изображений](/ru/reference/modules/astro-assets/#image-). Например, `aspectRatio` больше не поддерживается, так как теперь он автоматически вычисляется на основе атрибутов `width` и `height`.