Перейти к содержимому

Image and Assets API Reference

Это содержимое пока не доступно на вашем языке.

Добавлено в: astro@3.0.0

Astro provides built-in components and helper functions for optimizing and displaying your images. For features and usage examples, see our image guide.

The following helpers are imported from the virtual assets module:

import {
Image,
Picture,
getImage,
inferRemoteSize,
getConfiguredImageService,
imageConfig,
} from 'astro:assets';

The <Image /> component optimizes and transforms images.

This component can also be used to create responsive images that can adjust based on the size of their container or a device screen size and resolution.

src/components/MyComponent.astro
---
// import the Image component and the image
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---
<!-- `alt` is mandatory on the Image component -->
<Image src={myImage} alt="A description of my image." />
<!-- Output -->
<!-- Image is optimized, proper attributes are enforced -->
<img
src="/_astro/my_image.hash.webp"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>

The <Image /> component accepts the following listed properties and responsive image properties in addition to all properties accepted by the HTML <img> tag.

Type: ImageMetadata | string | Promise<{ default: ImageMetadata }>

The format of the src value of your image file depends on where your image file is located:

  • Local images in src/ - you must also import the image using a relative file path or configure and use an import alias. Then use the import name as the src value:

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    import myImportedImage from '../assets/my-local-image.png';
    ---
    <Image src={myImportedImage} alt="descriptive text" />
  • Images in the public/ folder - use the image’s file path relative to the public folder:

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    ---
    <Image
    src="/images/my-public-image.png"
    alt="descriptive text"
    width="200"
    height="150"
    />
  • Remote images - use the image’s full URL as the property value:

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    ---
    <Image
    src="https://example.com/remote-image.jpg"
    alt="descriptive text"
    width="200"
    height="150"
    />

Type: string

Use the required alt attribute to provide a string of descriptive alt text for images.

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/)

Section titled “width and height (required for images in public/)”

Type: number | `${number}` | undefined

These properties define the dimensions to use for the image.

When a layout type is set, these are automatically generated based on the image’s dimensions and in most cases should not be set manually.

When using images in their original aspect ratio, width and height are optional. These dimensions can be automatically inferred from image files located in src/. For remote images, add the inferSize attribute set to true on the <Image /> or <Picture /> component or use inferRemoteSize() function.

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

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

Добавлено в: astro@3.3.0

A list of pixel densities to generate for the image.

The densities attribute is not compatible with responsive images with a layout prop or image.layout config set, and will be ignored if set.

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.

src/components/MyComponent.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."
/>
<!-- Output -->
<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"
/>

Type: number[] | undefined

Добавлено в: astro@3.3.0

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 must also be provided.

The widths and sizes attributes will be automatically generated for responsive images using a layout property. Providing these values is generally not needed, but can be used to override any automatically generated values.

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.

src/components/MyComponent.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]}
sizes={`(max-width: 360px) 240px, (max-width: 720px) 540px, (max-width: 1600px) 720px, ${myImage.width}px`}
alt="A description of my image."
/>
<!-- Output -->
<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
"
sizes="
(max-width: 360px) 240px,
(max-width: 720px) 540px,
(max-width: 1600px) 720px,
1600px
"
alt="A description of my image."
width="1600"
height="900"
loading="lazy"
decoding="async"
/>

Type: string | undefined

Добавлено в: astro@3.3.0

Specifies the layout width of the image for each of a list of media conditions. Must be provided when specifying widths.

The widths and sizes attributes will be automatically generated for responsive images using a layout property. Providing these values is generally not needed, but can be used to override any automatically generated values.

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.

Type: ImageOutputFormat | undefined

You can optionally state the image file type output to be used.

By default, the <Image /> component will produce a .webp file.

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).

Type: boolean
Default: false

Добавлено в: astro@4.4.0

Allows you to set the original width and height of a remote image automatically.

By default, this value is set to false and you must manually specify both dimensions for your remote image.

Add inferSize to the <Image /> component (or inferSize: true to getImage()) to infer these values from the image content when fetched. This is helpful if you don’t know the dimensions of the remote image, or if they might change:

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
---
<Image src="https://example.com/cat.png" inferSize alt="A cat sleeping in the sun." />

inferSize can fetch the dimensions of a remote image from a domain that has not been authorized, however the image itself will remain unprocessed.

Type: boolean
Default: false

Добавлено в: astro@5.10.0

Allows you to automatically set the loading, decoding, and fetchpriority attributes to their optimal values for above-the-fold images.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} priority alt="A description of my image" />

When priority="true" (or the shorthand syntax priority) is added to the <Image /> or <Picture /> component, it will add the following attributes to instruct the browser to load the image immediately:

loading="eager"
decoding="sync"
fetchpriority="high"

These individual attributes can still be set manually if you need to customize them further.

Добавлено в: astro@3.3.0

The <Picture /> component generates an optimized image with multiple formats and/or sizes.

This component can also be used to create responsive images that can adjust based on the size of their container or a device screen size and resolution.

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." />
<!-- 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.png"
width="1600"
height="900"
decoding="async"
loading="lazy"
alt="A description of my image."
/>
</picture>

<Picture /> accepts all the properties of the <Image /> component, including responsive image properties, plus the following:

Type: ImageOutputFormat[]

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'].

Type: ImageOutputFormat

Format to use as a fallback value for the <img> tag. Defaults to .png for static images (or .jpg if the image is a JPG), .gif for animated images, and .svg for SVG files.

Type: HTMLAttributes<'picture'>

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.

src/components/MyComponent.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;" }}
/>
<!-- Output -->
<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>

Setting the layout property on an <Image /> or <Picture /> component creates a responsive image and enables additional property settings.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} alt="A description of my image." layout='constrained' width={800} height={600} />

When a layout is set, srcset and sizes attributes are automatically generated based on the image’s dimensions and the layout type. The previous <Image /> component will generate the following HTML output:

<img
src="/_astro/my_image.hash3.webp"
srcset="/_astro/my_image.hash1.webp 640w,
/_astro/my_image.hash2.webp 750w,
/_astro/my_image.hash3.webp 800w,
/_astro/my_image.hash4.webp 828w,
/_astro/my_image.hash5.webp 1080w,
/_astro/my_image.hash6.webp 1280w,
/_astro/my_image.hash7.webp 1600w"
alt="A description of my image"
sizes="(min-width: 800px) 800px, 100vw"
loading="lazy"
decoding="async"
fetchpriority="auto"
width="800"
height="600"
style="--fit: cover; --pos: center;"
data-astro-image="constrained"
>

The value for layout also defines the default styles applied to the <img> tag to determine how the image should resize according to its container:

Responsive Image Styles
:where([data-astro-image]) {
object-fit: var(--fit);
object-position: var(--pos);
}
:where([data-astro-image='full-width']) {
width: 100%;
}
:where([data-astro-image='constrained']) {
max-width: 100%;
}

You can override the default object-fit and object-position styles by setting the fit and position props on the <Image /> or <Picture /> component.

Type: 'constrained' | 'full-width' | 'fixed' | 'none'
Default: image.layout | 'none'

Добавлено в: astro@5.10.0

Defines a responsive image and determines how the image should resize when its container changes size. Can be used to override the default configured value for image.layout.

  • constrained - The image will scale down to fit the container, maintaining its aspect ratio, but will not scale up beyond the specified width and height, or the image’s original dimensions.

    Use this if you want the image to display at the requested size where possible, but shrink to fit smaller screens. This matches the default behavior for images when using Tailwind. If you’re not sure, this is probably the layout you should choose.

  • full-width - The image will scale to fit the width of the container, maintaining its aspect ratio.

    Use this for hero images or other images that should take up the full width of the page.

  • fixed - The image will maintain the requested dimensions and not resize. It will generate a srcset to support high density displays, but not for different screen sizes.

    Use this if the image will not resize, for example icons or logos smaller than any screen width, or other images in a fixed-width container.

  • none - The image will not be responsive. No srcset or sizes will be automatically generated, and no styles will be applied.

    This is useful if you have enabled a default layout, but want to disable it for a specific image.

For example, with constrained set as the default layout, you can override any individual image’s layout property:

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} alt="This will use constrained layout" width={800} height={600} />
<Image src={myImage} alt="This will use full-width layout" layout="full-width" />
<Image src={myImage} alt="This will disable responsive images" layout="none" />

Type: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
Default: image.objectFit | 'cover'

Добавлено в: astro@5.10.0

Enabled when the layout property is set or configured. Defines how a responsive image should be cropped if its aspect ratio is changed.

Values match those of CSS object-fit. Defaults to cover, or the value of image.objectFit if set. Can be used to override the default object-fit styles.

Type: string
Default: image.objectPosition | 'center'

Добавлено в: astro@5.10.0

Enabled when the layout property is set or configured. Defines the position of the image crop for a responsive image if the aspect ratio is changed.

Values match those of CSS object-position. Defaults to center, or the value of image.objectPosition if set. Can be used to override the default object-position styles.

Type: (options: UnresolvedImageTransform) => Promise<GetImageResult>

The getImage() function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an API Route. It also allows you to create your own custom <Image /> component.

This takes an options object with the same properties as the Image component (except alt) and returns a GetImageResult object.

The following example generates an AVIF background-image for a <div />:

src/components/Background.astro
---
import { getImage } from "astro:assets";
import myBackground from "../background.png"
const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---
<div style={`background-image: url(${optimizedBackground.src});`}><slot /></div>

Type: (url: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>

Добавлено в: astro@4.12.0

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 property.

import { inferRemoteSize } from 'astro:assets';
const { width, height } = await inferRemoteSize("https://example.com/cat.png");

Type: () => Promise<ImageService>

Добавлено в: astro@2.1.3

Retrieves the resolved image service.

Type: AstroConfig["image"]

Добавлено в: astro@3.0.9

The configuration options for images set by the user and merged with all defaults.

The following types are imported from the virtual assets module:

import type {
LocalImageProps,
RemoteImageProps,
} from "astro/assets";

Type: ImageSharedProps<T> & { src: ImageMetadata | Promise<{ default: ImageMetadata; }> }

Describes the properties of a local image. This ensures that src matches the shape of an imported image.

Learn more about imported images in src/ with an example usage.

Types:

  • ImageSharedProps<T> & { src: string; inferSize: true; }
  • ImageSharedProps<T> & { src: string; inferSize?: false | undefined; }

Describes the properties of a remote image. This ensures that when inferSize is not provided or is set to false, both width and height are required.

The following helpers are imported from the regular assets module:

import {
baseService,
getConfiguredImageService,
getImage,
isLocalService,
} from "astro/assets";

Type: Omit<LocalImageService, ‘transform’>

The built-in local image service which can be extended to create a custom image service.

The following example reuses the baseService to create a new image service:

src/image-service.ts
import { baseService } from "astro/assets";
const newImageService = {
getURL: baseService.getURL,
parseURL: baseService.parseURL,
getHTMLAttributes: baseService.getHTMLAttributes,
async transform(inputBuffer, transformOptions) {...}
}

See getConfiguredImageService() from astro:assets.

Type: (options: UnresolvedImageTransform, imageConfig: AstroConfig[‘image’]) => Promise<GetImageResult>

A function similar to getImage() from astro:assets with two required arguments: an options object with the same properties as the Image component and a second object for the image configuration.

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

Checks the type of an image service and returns true when this is a local service.

The following types are imported from the regular assets module:

import type {
LocalImageProps,
RemoteImageProps,
} from "astro/assets";

See LocalImageProps from astro:assets.

See RemoteImageProps from astro:assets.

The following helpers are imported from the utils directory in the regular assets module and can be used to build an image service:

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";

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

Добавлено в: astro@4.0.0

Determines whether a given remote resource, identified by its source URL, is allowed based on specified domains and remote patterns.

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`

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

Добавлено в: astro@4.0.0

Matches a given URL’s hostname against a specified hostname, with optional support for wildcard patterns.

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`

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

Добавлено в: astro@4.0.0

Matches a given URL’s pathname against a specified pattern, with optional support for wildcards.

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`

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

Добавлено в: astro@4.0.0

Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname.

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`

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

Добавлено в: astro@4.0.0

Checks if the given URL’s port matches the specified port. If no port is provided, it returns true.

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`

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

Добавлено в: astro@4.0.0

Compares the protocol of the provided URL with a specified protocol. This returns true if the protocol matches or if no protocol is provided.

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`

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

Добавлено в: astro@4.0.0

Determines if the given source is an ECMAScript Module (ESM) imported image.

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`

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

Добавлено в: astro@4.0.0

Determines if the provided source is a remote image URL in the form of a string.

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`

Type: (src: UnresolvedImageTransform[‘src’]) => Promise<string | ImageMetadata>

Добавлено в: astro@4.0.0

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.

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' }`

Type: (data: Uint8Array, src?: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>

Добавлено в: astro@4.0.0

Extracts image metadata such as dimensions, format, and orientation from the provided image data.

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
// }

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

Добавлено в: astro@5.7.0

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.

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([...])
// }

Type: (params: URLSearchParams) => Pick<ImageMetadata, ‘width’ | ‘height’ | ‘format’> | undefined

Добавлено в: astro@4.0.0

Retrieves the width, height, and format of an image from a URLSearchParams object. If any of these parameters are missing or invalid, the function returns undefined.

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'
// }

Type: (url: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>

Добавлено в: astro@4.0.0

Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata is available.

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'
// }

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

Добавлено в: astro@4.0.0

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>/<baseFilename>_<hash><outputExtension>

  • 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.
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'

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

Добавлено в: astro@4.0.0

Transforms the provided transform object into a hash string based on selected properties and the specified imageService.

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'

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

Добавлено в: astro@4.0.0

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.

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([...])
// }
import type {
GetImageResult,
ImageTransform,
UnresolvedImageTransform,
ImageMetadata,
ImageInputFormat,
ImageOutputFormat,
ImageQuality,
ImageQualityPreset,
RemotePattern,
ImageService,
ExternalImageService,
LocalImageService,
ImageServiceConfig,
} from "astro";

Type: object

Добавлено в: astro@2.2.0

Describes the result of the transformation after the call to getImage().

Type: Record<string, any>

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

Type: ImageTransform

Describes the transformation settings after validation.

Type: ImageTransform

Describes the original transformation settings.

Type: string

The path to the generated image.

Type: { values: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; url: string; }[]; attribute: string; }

Добавлено в: astro@3.3.0

An object describing how to render the srcset attribute.

Type: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; 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.

Type: string

A value ready to use in the srcset attribute.

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:

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.

Type: number | undefined

The width of the image.

Type: number | undefined

The height of the image.

Type: number[] | undefined

Добавлено в: astro@3.3.0

A list of widths to generate for the image.

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

Добавлено в: astro@3.3.0

A list of pixel densities to generate for the image.

Type: ImageQuality | undefined

The desired quality for the output image.

Type: ImageOutputFormat | undefined

The desired format for the output image.

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

Добавлено в: astro@5.0.0

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

Type: string | undefined

Добавлено в: astro@5.0.0

Controls the value for the object-position CSS property.

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 with a different src type and an additional inferSize property.

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.

Type: boolean

Determines whether the width and height of the image should be inferred.

See also the inferSize attribute available on <Image />.

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

Добавлено в: astro@2.1.3

Describes the data collected during image import. This contains the following properties:

Type: string

The absolute path of the image on the filesystem.

Type: number

The width of the image.

Type: number

The height of the image.

Type: ImageInputFormat

The format of the image.

Type: number

Добавлено в: astro@2.8.3

The image orientation when its metadata contains this information.

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

Добавлено в: astro@2.2.0

Describes a union of supported formats for imported images.

Type: string | "jpeg" | "jpg" | "png" | "webp" | "svg" | "avif"

Добавлено в: astro@2.2.0

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

Type: ImageQualityPreset | number

Добавлено в: astro@2.2.0

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

Type: string | "low" | "mid" | "high" | "max"

Добавлено в: astro@2.2.0

Defines the available presets to control image quality, extensible with any string.

Type: { hostname?: string; pathname?: string; protocol?: string; port?: string; }

Добавлено в: astro@5.14.2

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

Type: ExternalImageService | LocalImageService

Defines the hooks that a local or external image service must provide.

Type: object

Defines the hooks that an external image transformation service must provide. This requires a getUrl() hook and supports three additional hooks.

Learn how to build external services in the Image Service API reference with example usage.

Type: object

Defines the hooks that a local image transformation service must provide. This requires getUrl(), parseUrl(), and transform() hooks, and supports additional hooks.

Learn how to build local services in the Image Service API reference with example usage.

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

Добавлено в: astro@2.3.3

Describes the configuration object for an image service. This contains the following properties:

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.

Type: Record<string, any>

A configuration object passed to the image service. The shape depends on the specific service being used.

Внести свой вклад Сообщество Поддержать