跳转到内容

图像和资源 API 参考

添加于: astro@3.0.0

Astro 提供了内置组件和辅助函数来优化和显示你的图像。有关功能和用法示例,请参阅我们的图像指南

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

<Image /> 组件用于优化和转换图像。

此组件还可用于创建响应式图像,这些图像可以根据其容器的大小或设备的屏幕尺寸和分辨率进行调整。

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 /> 组件除了接受 HTML <img> 标签的所有属性外,还接受下面列出的属性和响应式图像属性

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

图像文件的 src 值的格式取决于图像文件的位置

  • src/ 中的本地图像 - 你必须同时导入图像,使用相对文件路径或配置并使用导入别名。然后使用导入名称作为 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/ 文件夹中的图像 - 使用图像相对于 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"
    />

类型: string

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

如果图像只是装饰性的(即对理解页面内容没有帮助),请设置 alt="",以便屏幕阅读器和其他辅助技术知道忽略该图像。

width 和 height (对于 public/ 中的图像是必需的)
标题为“width 和 height (对于 public/ 中的图像是必需的)”的部分

类型: number | undefined

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

当设置了 layout 类型时,这些值会根据图像的尺寸自动生成,在大多数情况下不应手动设置。

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

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

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

添加于: astro@3.3.0

为图像生成的一系列像素密度。

densities 属性与设置了 layout 属性或 image.layout 配置的响应式图像不兼容,如果设置了将被忽略。

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

等于大于原始图像宽度的密度将被忽略,以避免图像被放大。

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

添加于: astro@3.3.0

为图像生成的一系列宽度。

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

对于使用 layout 属性的响应式图像,widthssizes 属性将自动生成。通常不需要提供这些值,但可以用来覆盖任何自动生成的值。

使用此值时,请勿为 densities 提供值。这两个值中只有一个可用于生成 srcset

大于原始图像的宽度将被忽略,以避免图像被放大。

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

类型: string | undefined

添加于: astro@3.3.0

为一系列媒体条件中的每一个指定图像的布局宽度。在指定 widths 时必须提供。

对于使用 layout 属性的响应式图像,widthssizes 属性将自动生成。通常不需要提供这些值,但可以用来覆盖任何自动生成的值。

constrainedfull-width 图像生成的 sizes 属性是基于这样的假设:当视口小于图像宽度时,图像会以接近屏幕全宽的尺寸显示。如果情况显著不同(例如,在小屏幕上它位于多列布局中),你可能需要手动调整 sizes 属性以获得最佳效果。

类型: ImageOutputFormat | undefined

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

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

类型: ImageQuality | undefined

quality 是一个可选属性,可以是

  • 一个预设值(lowmidhighmax),它会在不同格式之间自动归一化。
  • 一个从 0100 的数字(在不同格式之间有不同的解释)。

类型: boolean
默认值: false

添加于: astro@4.4.0

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

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

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

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 可以从未授权的域获取远程图像的尺寸,但图像本身不会被处理。

类型: boolean
默认值: false

添加于: astro@5.10.0

允许你为首屏图像自动将 loadingdecodingfetchpriority 属性设置为最佳值。

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

priority="true"(或简写语法 priority)被添加到 <Image /><Picture /> 组件时,它将添加以下属性来指示浏览器立即加载图像

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

如果你需要进一步自定义,这些单独的属性仍然可以手动设置。

添加于: astro@3.3.0

<Picture /> 组件生成一个具有多种格式和/或尺寸的优化图像。

此组件还可用于创建响应式图像,这些图像可以根据其容器的大小或设备的屏幕尺寸和分辨率进行调整。

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 /> 接受 <Image /> 组件的所有属性,包括响应式图像属性,以及以下属性

类型: ImageOutputFormat[]

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

类型: ImageOutputFormat

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

类型: HTMLAttributes<'picture'>

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

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

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>

<Image /><Picture /> 组件上设置 layout 属性可以创建响应式图像,并启用额外的属性设置。

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

当设置了布局时,srcsetsizes 属性会根据图像的尺寸和布局类型自动生成。前面的 <Image /> 组件将生成以下 HTML 输出

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

layout 的值也定义了应用于 <img> 标签的默认样式,以确定图像应如何根据其容器调整大小

响应式图像样式
: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%;
}

你可以通过在 <Image /><Picture /> 组件上设置 fitposition 属性来覆盖默认的 object-fitobject-position 样式。

类型: 'constrained' | 'full-width' | 'fixed' | 'none'
默认: image.layout | 'none'

添加于: astro@5.10.0

定义一个响应式图像,并确定当其容器大小改变时图像应如何调整大小。可用于覆盖image.layout的默认配置值。

  • constrained - 图像将按比例缩小以适应容器,保持其纵横比,但不会放大到超出指定的 widthheight 或图像的原始尺寸。

    如果你希望图像在可能的情况下以请求的尺寸显示,但在较小的屏幕上收缩以适应,请使用此布局。这与使用 Tailwind 时图像的默认行为相匹配。如果你不确定,这可能就是你应该选择的布局。

  • full-width - 图像将按比例缩放以适应容器的宽度,并保持其纵横比。

    用于主图或其他应占据页面全宽的图像。

  • fixed - 图像将保持请求的尺寸并且不会调整大小。它将生成一个 srcset 以支持高密度显示,但不会为不同的屏幕尺寸生成。

    如果图像不会调整大小,请使用此选项,例如小于任何屏幕宽度的图标或徽标,或固定宽度容器中的其他图像。

  • none - 图像将不是响应式的。不会自动生成 srcsetsizes,也不会应用任何样式。

    如果你已启用默认布局,但希望对特定图像禁用它,这将非常有用。

例如,如果将 constrained 设置为默认布局,你可以覆盖任何单个图像的 layout 属性

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

类型: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
默认: image.objectFit | 'cover'

添加于: astro@5.10.0

当设置或配置了 layout 属性时启用。定义当响应式图像的纵横比改变时应如何裁剪。

值与 CSS object-fit 的值相匹配。默认为 cover,如果设置了,则为image.objectFit的值。可用于覆盖默认的 object-fit 样式。

类型: string
默认: image.objectPosition | 'center'

添加于: astro@5.10.0

当设置或配置了 layout 属性时启用。定义当响应式图像的纵横比改变时图像裁剪的位置。

值与 CSS object-position 的值相匹配。默认为 center,如果设置了,则为image.objectPosition的值。可用于覆盖默认的 object-position 样式。

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

getImage() 函数用于生成不直接在 HTML 中使用的图像,例如在 API 路由中使用。它还允许你创建自己的自定义 <Image /> 组件。

getImage() 接受一个选项对象,其属性与 Image 组件的属性相同(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>

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

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

添加于: astro@4.12.0

一个用于推断远程图像尺寸的函数。这可以作为传递 inferSize 属性的替代方案。

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