Skip to content

资源 API 参考

Added in: astro@3.0.0

Astro 提供内置组件和辅助函数来优化和显示图片。有关功能和使用示例,查看我们的图片指南

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

¥Imports from astro:assets

import {
Image,
Picture,
getImage,
inferRemoteSize,
} from 'astro:assets';
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."
/>

¥Image properties

除了下面描述的属性之外,<Image /> 组件还接受 HTML <img> 标记接受的所有属性。

¥The <Image /> component accepts all properties accepted by the HTML <img> tag in addition to the properties described below.

¥src (required)

类型:ImageMetadata | string | Promise<{ default: ImageMetadata }>

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

图片文件的 src 值的格式取决于图片文件所在的位置:

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

  • src/ 中的本地图片 - 你还必须使用相对文件路径导入图片或配置和使用 import alias。然后使用导入名称作为 src 值:

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    import myImportedImage from '../assets/my-local-image.png';
    ---
    <Image src={myImportedImage} alt="descriptive text" />
  • public/ 文件夹中的图片 - 使用相对于公共文件夹的图片文件路径:

    src/pages/index.astro
    ---
    import { Image } from 'astro:assets';
    ---
    <Image
    src="/images/my-public-image.png"
    alt="descriptive text"
    width="200"
    height="150"
    />
  • 远程图片 - 使用图片的完整 URL 作为属性值:

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

¥alt (required)

类型:string

¥Type: string

使用必需的 alt 属性为图片提供 描述性替代文本 字符串。

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

如果图片仅仅是装饰性的(即无助于理解页面),请设置 alt="" 以便屏幕阅读器和其他辅助技术知道忽略该图片。

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

宽度和高度(public/ 中的图片所需)
标题部分 宽度和高度(public/ 中的图片所需)

¥width and height (required for images in public/)

类型:number | undefined

¥Type: number | undefined

这些属性定义了图片使用的尺寸。

¥These properties define the dimensions to use for the image.

使用原始纵横比的图片时,widthheight 是可选的。这些尺寸可以从位于 src/ 中的图片文件中自动推断出来。对于远程图片,请在 <Image /><Picture /> 组件上添加 inferSize 属性设置为 true 或使用 inferRemoteSize() 功能

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

但是,这两个属性对于存储在 public/ 文件夹中的图片都是必需的,因为 Astro 无法分析这些文件。

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

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

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

Added in: astro@3.3.0

为图片生成的像素密度列表。

¥A list of pixel densities to generate for the image.

如果提供,该值将用于在 <img> 标记上生成 srcset 属性。使用此值时,请勿为 widths 提供值。

¥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"
/>

类型:number[] | undefined

¥Type: number[] | undefined

Added in: astro@3.3.0

为图片生成的宽度列表。

¥A list of widths to generate for the image.

如果提供,该值将用于在 <img> 标记上生成 srcset 属性。还必须提供 sizes 属性

¥If provided, this value will be used to generate a srcset attribute on the <img> tag. A sizes property must also be provided.

使用此值时,请勿为 densities 提供值。只能使用这两个值之一来生成 srcset

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

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

类型:ImageOutputFormat | undefined

¥Type: ImageOutputFormat | undefined

你可以选择指定要使用的 图片文件类型 输出。

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

默认情况下,<Image /> 组件将生成 .webp 文件。

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

类型:ImageQuality | undefined

¥Type: ImageQuality | undefined

quality 是可选属性,可以是:

¥quality is an optional property that can either be:

  • 在格式之间自动标准化的预设(lowmidhighmax)。

  • 0100 的数字(不同格式的解释不同)。

类型:boolean

¥Type: boolean

Added in: astro@4.4.0

允许你自动设置远程图片的原始 widthheight

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

默认情况下,此值设置为 false,你必须手动指定远程图片的两个尺寸。

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

inferSize 添加到 <Image /> 组件(或将 inferSize: true 添加到 getImage())以在获取时从图片内容中推断这些值。如果你不知道远程图片的尺寸,或者它们可能会发生变化,这将非常有用:

¥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:

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

inferSize 可以获取 来自未经授权的域的远程图片 的尺寸,但图片本身将保持未处理状态。

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

Added in: astro@3.3.0

使用内置的 <Picture /> Astro 组件显示具有多种格式和/或尺寸的响应式图片。

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

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 properties

<Picture /> 接受 <Image /> 组件 的所有属性,以及以下属性:

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

类型:ImageOutputFormat[]

¥Type: ImageOutputFormat[]

用于 <source> 标签的图片格式数组。条目将按照列出的顺序添加为 <source> 元素,并且此顺序决定显示的格式。为了获得最佳性能,请首先列出最现代的格式(例如 webpavif)。默认情况下,该值设置为 ['webp']

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

类型:ImageOutputFormat

¥Type: ImageOutputFormat

用作 <img> 标记后备值的格式。对于静态图片,默认为 .png(如果图片是 JPG,则为 .jpg),对于动画图片,默认为 .gif,对于 SVG 文件,默认为 .svg

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

类型:HTMLAttributes<'picture'>

¥Type: HTMLAttributes<'picture'>

要添加到 <picture> 标记的属性对象。

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

使用此属性将属性应用到外部 <picture> 元素本身。直接应用于 <Picture /> 组件的属性将应用于内部 <img> 元素,用于图片转换的属性除外。

¥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>

类型:(options: UnresolvedImageTransform) => Promise<GetImageResult>

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

getImage() 函数旨在生成要在其他地方使用的图片,而不是直接在 HTML 中使用,例如在 API 路由 中。它还允许你创建自己的自定义 <Image /> 组件。

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

getImage() 使用 与 Image 组件具有相同的属性 的选项对象(alt 除外)。

¥getImage() takes an options object with the same properties as the Image component (except alt).

---
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});`}></div>

它返回具有以下类型的对象:

¥It returns an object with the following type:

type GetImageResult = {
/* Additional HTML attributes needed to render the image (width, height, style, etc..) */
attributes: Record<string, any>;
/* 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;
};
}

类型:(url: string) => Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>

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

Added in: astro@4.12.0

推断远程图片​​尺寸的函数。这可以用作传递 inferSize 属性的替代方法。

¥A function to infer the dimensions of remote images. 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");
Astro 中文网 - 粤ICP备13048890号