图片和资源 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.
从 astro:assets
导入
标题部分 从 astro:assets 导入¥Imports from astro:assets
import { Image, Picture, getImage, inferRemoteSize, } from 'astro:assets';
<Image />
标题部分 <Image /><Image />
组件用于优化和转换图片。
¥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.
---// import the Image component and the imageimport { 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
除了 HTML <img>
标签接受的所有属性外,<Image />
组件还接受以下列出的属性和 响应式图片属性。
¥The <Image />
component accepts the following listed properties and responsive image properties in addition to all properties accepted by the HTML <img>
tag.
源代码(必填)
标题部分 源代码(必填)¥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';---<Imagesrc="/images/my-public-image.png"alt="descriptive text"width="200"height="150"/> -
远程图片 - 使用图片的完整 URL 作为属性值:
src/pages/index.astro ---import { Image } from 'astro:assets';---<Imagesrc="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.
设置 layout
类型后,这些属性会根据图片的尺寸自动生成,大多数情况下无需手动设置。
¥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.
使用原始纵横比的图片时,width
和 height
是可选的。这些尺寸可以从位于 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.
densities
标题部分 densities类型:(number | `${number}x`)[] | undefined
¥Type: (number | `${number}x`)[] | undefined
astro@3.3.0
为图片生成的像素密度列表。
¥A list of pixel densities to generate for the image.
densities
属性与使用 layout
属性的响应式图片不兼容,如果设置该属性,它将被忽略。
¥The densities
attribute is not compatible with responsive images using a layout
property and will be ignored if set.
如果提供,该值将用于在 <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.
---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"/>
widths
标题部分 widths类型:number[] | undefined
¥Type: number[] | undefined
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.
对于使用 layout
属性的响应式图片,将自动生成 widths
和 sizes
属性。通常不需要提供这些值,但可以用来覆盖任何自动生成的值。
¥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.
使用此值时,请勿为 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"/>
sizes
标题部分 sizes类型:string | undefined
¥Type: string | undefined
astro@3.3.0
为一系列媒体条件中的每一种指定图片的布局宽度。指定 widths
时必须提供。
¥Specifies the layout width of the image for each of a list of media conditions. Must be provided when specifying widths
.
对于使用 layout
属性的响应式图片,将自动生成 widths
和 sizes
属性。通常不需要提供这些值,但可以用来覆盖任何自动生成的值。
¥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.
为 constrained
和 full-width
图片生成的 sizes
属性基于以下假设:当视口小于图片宽度时,图片的显示接近屏幕的全宽。如果差异很大(例如,在小屏幕上采用多列布局),你可能需要手动调整 sizes
属性以获得最佳效果。
¥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类型: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.
quality
标题部分 quality类型:ImageQuality | undefined
¥Type: ImageQuality | undefined
quality
是可选属性,可以是:
¥quality
is an optional property that can either be:
-
在格式之间自动标准化的预设(
low
、mid
、high
、max
)。 -
从
0
到100
的数字(不同格式的解释不同)。
inferSize
标题部分 inferSize类型:boolean
默认:false
¥Type: boolean
Default: false
astro@4.4.0
允许你自动设置远程图片的原始 width
和 height
。
¥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.
priority
标题部分 priority类型:boolean
默认:false
¥Type: boolean
Default: false
astro@5.10.0
新
允许你自动将 loading
、decoding
和 fetchpriority
属性设置为首屏图片的最佳值。
¥Allows you to automatically set the loading
, decoding
, and fetchpriority
attributes to their optimal values for above-the-fold images.
---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 />
组件时,它将添加以下属性以指示浏览器立即加载图片:
¥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.
<Picture />
标题部分 <Picture />
Added in:
astro@3.3.0
<Picture />
组件生成具有多种格式和/或尺寸的优化图片。
¥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.
---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, including responsive image properties, plus the following:
formats
标题部分 formats类型:ImageOutputFormat[]
¥Type: ImageOutputFormat[]
用于 <source>
标签的图片格式数组。条目将按照列出的顺序添加为 <source>
元素,并且此顺序决定显示的格式。为了获得最佳性能,请首先列出最现代的格式(例如 webp
或 avif
)。默认情况下,该值设置为 ['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']
.
fallbackFormat
标题部分 fallbackFormat类型: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.
pictureAttributes
标题部分 pictureAttributes类型: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.
---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>
响应式图片属性
标题部分 响应式图片属性¥Responsive image properties
在 <Image />
或 <Picture />
组件上设置 layout
属性会创建响应式图片并启用其他属性设置。
¥Setting the layout
property on an <Image />
or <Picture />
component creates a responsive image and enables additional property settings.
---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} />
设置布局后,srcset
和 sizes
属性会根据图片的尺寸和布局类型自动生成。之前的 <Image />
组件将生成以下 HTML 输出:
¥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">
layout
的值还定义了应用于 <img>
标签的默认样式,用于确定图片如何根据其容器调整大小:
¥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:
: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 />
组件上设置 fit
和 position
属性来覆盖默认的 object-fit
和 object-position
样式。
¥You can override the default object-fit
and object-position
styles by setting the fit
and position
props on the <Image />
or <Picture />
component.
layout
标题部分 layout类型:'constrained' | 'full-width' | 'fixed' | 'none'
默认:image.layout | 'none'
¥Type: 'constrained' | 'full-width' | 'fixed' | 'none'
Default: image.layout | 'none'
astro@5.10.0
新
定义 响应式图片 并确定当容器大小发生变化时图片应如何调整大小。可用于覆盖 image.layout
的默认配置值。
¥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
- 图片将缩小以适应容器,保持其宽高比,但不会放大到超出指定的width
和height
或图片的原始尺寸。如果你希望图片尽可能以请求的大小显示,但会缩小以适应较小的屏幕,请使用此选项。这与使用 Tailwind 时图片的默认行为一致。如果你不确定,这可能是你应该选择的布局。
-
full-width
- 图片将缩放以适应容器的宽度,保持其宽高比。将此加载器用于英雄图片或其他应占据整个页面宽度的图片。
-
fixed
- 图片将保持请求的尺寸,不会调整大小。它将生成一个srcset
以支持高密度显示器,但不适用于不同的屏幕尺寸。如果图片无法调整大小,例如图标或徽标小于任何屏幕宽度,或固定宽度容器中的其他图片,请使用此选项。
-
none
- 图片将不具有响应式布局。不会自动生成srcset
或sizes
,也不会应用任何样式。如果你已启用默认布局,但想要为特定图片禁用它,这将非常有用。
例如,将 constrained
设置为默认布局后,你可以覆盖任何单个图片的 layout
属性:
¥For example, with constrained
set as the default layout, you can override any individual image’s layout
property:
---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" />
fit
标题部分 fit类型:'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
默认:image.objectFit | 'cover'
¥Type: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
Default: image.objectFit | 'cover'
astro@5.10.0
新
设置或配置 layout
属性后启用。定义响应式图片在其宽高比发生变化时应如何裁剪。
¥Enabled when the layout
property is set or configured. Defines how a responsive image should be cropped if its aspect ratio is changed.
值与 CSS object-fit
的值匹配。默认为 cover
,或如果设置,则为 image.objectFit
的值。可用于覆盖默认的 object-fit
样式。
¥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.
position
标题部分 position类型:string
默认:image.objectPosition | 'center'
¥Type: string
Default: image.objectPosition | 'center'
astro@5.10.0
新
设置或配置 layout
属性后启用。定义响应式图片在宽高比发生变化时裁剪的位置。
¥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.
值与 CSS object-position
的值匹配。默认为 center
,或如果设置,则为 image.objectPosition
的值。可用于覆盖默认的 object-position
样式。
¥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.
priority
标题部分 priority类型:boolean
默认:false
¥Type: boolean
Default: false
astro@5.10.0
新
设置或配置 layout
属性后启用。如果设置,则立即加载响应式图片。否则,图片将被延迟加载。将其用于最大的首屏图片。默认为 false
。
¥Enabled when the layout
property is set or configured. If set, eagerly loads a responsive image. Otherwise, images will be lazy-loaded. Use this for your largest above-the-fold image. Defaults to false
.
getImage()
标题部分 getImage()类型:(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; };}
inferRemoteSize()
标题部分 inferRemoteSize()类型:(url: string) => Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>
¥Type: (url: string) => Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>
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");