图片与资源 API 参考
添加于:
astro@3.0.0
Astro 提供了内置组件和辅助函数来优化和显示图像。有关功能和使用示例,请参阅我们的图像指南。
从 astro:assets 导入
Section titled “从 astro:assets 导入”以下辅助函数从虚拟资源模块导入:
import { Image, Picture, getImage, inferRemoteSize, getConfiguredImageService, imageConfig,} from 'astro:assets';<Image />
Section titled “<Image />”<Image /> 组件能优化并转换图像。
该组件还可用于创建能根据容器尺寸或设备屏幕大小及分辨率自动调整的 响应式图片 。
---// 导入图像组件和图片import { Image } from 'astro:assets';import myImage from "../assets/my_image.png"; // 图片分辨率是 1600x900---
<!-- `alt` 在 Image 组件中是必需的属性 --><Image src={myImage} alt="A description of my image." /><!-- 输出 --><!-- Image 组件已经过优化,并且对应的属性也被强制使用。 --><img src="/_astro/my_image.hash.webp" width="1600" height="900" decoding="async" loading="lazy" alt="一段关于我图片的描述。"/><Image /> 组件除接受 HTML <img> 标签的所有属性外,还支持以下列出的属性及 响应式图片属性。
src (必须)
Section titled “src (必须)”类型: 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';---<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 (必须)
Section titled “alt (必须)”类型: string
使用必需的 alt 属性为图像提供 描述性的 alt 文本。
如果图像仅仅是装饰性的(即对理解页面没有帮助),请设置 alt="" 以便屏幕阅读器和其他辅助技术知道忽略该图像。
width 和 height(对于 public/ 中的图像是必须的)
Section titled “width 和 height(对于 public/ 中的图像是必须的)”类型: number | `${number}` | undefined
这些属性定义了要用于图像的尺寸。
当设置了 layout 类型时,这些属性会根据图像尺寸自动生成,在大多数情况下不应手动设置。
当使用保持原始宽高比的图像时,width 和 height 是可选的。这些尺寸可以自动从位于 src/ 中的图像文件自动推断出来。而对于远程图像,请将 <Image /> 或 <Picture /> 组件上的 inferSize 属性设置为 true,或使用 inferRemoteSize() 函数。
但是,对于存储在你的 public/ 文件夹中的图像,这两个属性都是必需的,因为 Astro 无法分析这些文件。
densities
Section titled “densities”类型: (number | `${number}x`)[] | undefined
astro@3.3.0
为图像生成的像素密度列表。
densities 属性与设置了 layout 属性或 image.layout 配置的 响应式图像 不兼容,若同时设置将被忽略。
如果提供了该值,将会在 <img> 标签上生成一个 srcset 属性。在使用此值时,请不要提供 widths 的值。
与原始图像相同或大于原始图像宽度的像素密度会被忽略,以避免放大图像。
---import { Image } from 'astro:assets';import myImage from '../assets/my_image.png';---<Image src={myImage} width={myImage.width / 2} densities={[1.5, 2]} alt="我的图片描述"/><!-- 输出 --><img src="/_astro/my_image.hash.webp" srcset=" /_astro/my_image.hash.webp 1.5x /_astro/my_image.hash.webp 2x " alt="我的图片描述" width="800" height="450" loading="lazy" decoding="async"/>widths
Section titled “widths”类型: number[] | undefined
astro@3.3.0
为图像生成的宽度列表。
如果提供了该值,将会在 <img> 标签上生成一个 srcset 属性。但还需提供一个 sizes 属性。
widths 和 sizes 属性将通过 layout 属性自动生成,用于响应式图像。通常无需提供这些值,但可用于覆盖任何自动生成的值。
在使用该值时,请不要提供 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="我的图片描述"/><!-- 输出 --><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="我的图片描述" width="1600" height="900" loading="lazy" decoding="async"/>类型: string | undefined
astro@3.3.0
指定图像在各类媒体查询条件下的布局宽度。在指定 widths 时必须提供此参数。
响应式图片的 widths 和 sizes 属性将通过布局属性自动生成。通常无需手动提供这些值,但可用于覆盖任何自动生成的值。
针对 constrained 和 full-width 图片自动生成的 sizes 属性,其计算前提是当视口宽度小于图片宽度时,图片会以接近屏幕全宽的方式显示。若实际布局与此存在显著差异(例如在小屏幕设备上采用多栏布局),则可能需要手动调整 sizes 属性以获得最佳效果。
format
Section titled “format”类型: ImageOutputFormat | undefined
你可以选择指定要使用的 图像文件类型 输出。
默认情况下,<Image /> 组件将生成 .webp 文件。
quality
Section titled “quality”类型: ImageQuality | undefined
quality 是一个可选属性,可以是:
- 一个预设值(
low、mid、high、max),可以在不同格式之间自动标准化。 - 一个从
0到100的数字(不同格式之间的表现不同)。
inferSize
Section titled “inferSize”类型: boolean
默认值: false
astro@4.4.0
允许你自动设置远程图像的原始 width 和 height。
默认情况下,这个值被设置为 false,你必须手动指定远程图片的宽度和高度。
在 <Image /> 组件中添加 inferSize(或者在 getImage() 中添加 inferSize: true),以便在获取时从图片内容中推断这些值。如果你不知道远程图片的尺寸,或者这些尺寸可能会变化,这个属性对你会很有帮助:
---import { Image } from 'astro:assets';---<Image src="https://example.com/cat.png" inferSize alt="一只猫在阳光下睡觉。" />inferSize 能够获取来自未经授权域的 远程图片的尺寸,但图片本身将保持未处理状态。
priority
Section titled “priority”类型: boolean
默认值: false
astro@5.10.0
可自动为首屏图片设置 loading、decoding,和 fetchpriority 属性至最佳值。
---import { Image } from 'astro:assets';import myImage from '../assets/my_image.png';---<Image src={myImage} priority alt="A description of my image" />当在 <Image /> 或 <Picture /> 组件中添加 priority="true"(或简写语法 priority )时,它将添加以下属性以指示浏览器立即加载图像:
loading="eager"decoding="sync"fetchpriority="high"如需进一步定制,这些独立属性仍可手动设置。
<Picture />
Section titled “<Picture />”
添加于:
astro@3.3.0
<Picture /> 组件可以生成具有多种格式和(或)尺寸的优化后的图像。
该组件还可用于创建能根据容器尺寸或设备屏幕大小及分辨率自动调整的 响应式图片 。
---import { Picture } from 'astro:assets';import myImage from "../assets/my_image.png"; // 图像的分辨率为 1600x900---
<!-- 在图片组件上 `alt` 属性是必需的 --><Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." /><!-- 输出 --><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 /> 组件 的所有属性(包括 响应式图片属性),以及以下属性:
formats
Section titled “formats”类型: ImageOutputFormat[]
一个图像格式的数组,用于 <source> 标签。数组内的元素将按照列出的顺序添加为 <source> 元素,并且此顺序决定显示哪种格式。为了获得最佳性能,请首先列出最现代化的格式(例如 webp 或 avif)。默认情况下,它被设置为 ['webp']。
fallbackFormat
Section titled “fallbackFormat”用于作为 <img> 标签的回退值的格式。对于静态图像,默认为 .png(如果图像是 JPG,则默认为 .jpg);对于动画图像,默认为 .gif;对于 SVG 文件,默认为 .svg。
pictureAttributes
Section titled “pictureAttributes”类型: HTMLAttributes<'picture'>
一个被添加到 <picture> 标签的属性对象。
使用该属性可将属性应用于外部的 <picture> 元素本身。除了用于图像转换的属性外,直接应用于 <Picture /> 组件的属性将应用于内部的 <img> 元素。
---import { Picture } from "astro:assets";import myImage from "../my_image.png"; // Image 为 1600x900---
<Picture src={myImage} alt="我的图片描述。" pictureAttributes={{ style: "background-color: red;" }}/><!-- 输出 --><picture style="background-color: red;"> <source srcset="/_astro/my_image.hash.webp" type="image/webp" /> <img src="/_astro/my_image.hash.png" alt="我的图片描述。" width="1600" height="900" loading="lazy" decoding="async" /></picture>响应式图片属性
Section titled “响应式图片属性”在 <Image /> 或 <Picture /> 组件上设置 layout 属性会创建一个响应式图片,并启用其他属性设置。
---import { Image } from 'astro:assets';import myImage from '../assets/my_image.png';---<Image src={myImage} alt="我的图片描述。" layout='constrained' width={800} height={600} />设置布局后,会根据图片的尺寸和布局类型自动生成 srcset 和 sizes 属性。前面的 <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="我的图片描述" 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 /> 组件上设置 fit 和 position 属性来覆盖默认的 object-fit 和 object-position 样式。
layout
Section titled “layout”类型: 'constrained' | 'full-width' | 'fixed' | 'none'
默认值: image.layout | 'none'
astro@5.10.0
定义一个响应式图片,并确定当容器大小改变时图片应如何调整大小。可用于覆盖 image.layout 的默认配置值。
-
constrained- 图片将按比例缩小以适应容器,保持其宽高比,但不会放大超过指定的width和height或图片的原始尺寸。如果你希望图片在可能的情况下以请求的尺寸显示,但在较小的屏幕上收缩以适应,请使用此选项。这与使用 Tailwind 时图片的默认行为相匹配。如果你不确定,这可能是你应该选择的布局。
-
full-width- 图片将按比例缩放以适应容器的宽度,保持其宽高比。用于主视觉图片或其他应占据页面整个宽度的图片。
-
fixed- 图片将保持请求的尺寸并且不会调整大小。它会生成一个srcset以支持高密度显示,但不会为不同的屏幕尺寸生成。如果图片不会调整大小,例如图标或小于任何屏幕宽度的徽标,或其他固定宽度容器中的图片,请使用此选项。
-
none- 图片将不是响应式的。不会自动生成srcset或sizes,也不会应用任何样式。如果你已启用默认布局,但希望为特定图片禁用它,这很有用。
例如,将 constrained 设置为默认布局,你可以覆盖任何单个图片的 layout 属性:
---import { Image } from 'astro:assets';import myImage from '../assets/my_image.png';---<Image src={myImage} alt="这将使用 constrained 布局" width={800} height={600} /><Image src={myImage} alt="这将使用 full-width 布局" layout="full-width" /><Image src={myImage} alt="这将禁用响应式图片" layout="none" />类型: 'contain' | 'cover' | 'fill' | 'none' | 'scale-down'
默认值: image.objectFit | 'cover'
astro@5.10.0
当设置或配置了 layout 属性时启用。定义当宽高比改变时,响应式图片应如何裁剪。
值与 CSS object-fit 的值相匹配。默认为 cover,如果设置了,则为 image.objectFit 的值。可用于覆盖默认的 object-fit 样式。
position
Section titled “position”类型: string
默认值: image.objectPosition | 'center'
astro@5.10.0
当设置或配置了 layout 属性时启用。定义当宽高比改变时,响应式图片的裁剪位置。
值与 CSS object-position 的值相匹配。默认为 center,如果设置了,则为 image.objectPosition 的值。可用于覆盖默认的 object-position 样式。
getImage()
Section titled “getImage()”类型: (options: UnresolvedImageTransform) => Promise<GetImageResult>
getImage() 依赖于仅在服务器上可用的 API,当在客户端使用时会导致构建失败。
getImage()函数旨在生成用于在 HTML 之外的其他地方所使用的图像,例如在 API 路由 中。它还允许你创建自定义的 <Image /> 组件。
该函数接受一个选项对象,其中包含与 Image 组件相同的属性(除了 alt),并返回一个 GetImageResult 对象。
以下示例为 <div /> 生成一个 AVIF background-image:
---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>inferRemoteSize()
Section titled “inferRemoteSize()”类型: (url: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>
astro@4.12.0
自动设置远程图像原始 width 和 height 的函数。可以作为传递 inferSize 属性的替代方法。
import { inferRemoteSize } from 'astro:assets';const { width, height } = await inferRemoteSize("https://example.com/cat.png");getConfiguredImageService()
Section titled “getConfiguredImageService()”类型: () => Promise<ImageService>
astro@2.1.3
获取已解析的 图像服务。
imageConfig
Section titled “imageConfig”astro@3.0.9
用户设置并与所有默认值合并后的 图像配置选项。
astro:assets 类型
Section titled “astro:assets 类型”以下类型从虚拟资源模块导入:
import type { LocalImageProps, RemoteImageProps,} from "astro/assets";LocalImageProps
Section titled “LocalImageProps”类型: ImageSharedProps<T> & { src: ImageMetadata | Promise<{ default: ImageMetadata; }> }
src/ 中导入图像的示例用法。
RemoteImageProps
Section titled “RemoteImageProps”类型:
ImageSharedProps<T> & { src: string; inferSize: true; }ImageSharedProps<T> & { src: string; inferSize?: false | undefined; }
描述远程图像的属性。确保当 inferSize 未提供或设置为 false 时,width 和 height 都是必需的。
从 astro/assets 导入
Section titled “从 astro/assets 导入”以下辅助函数从常规资源模块导入:
import { baseService, getConfiguredImageService, getImage, isLocalService,} from "astro/assets";baseService
Section titled “baseService”类型: Omit<LocalImageService, ‘transform’>
可扩展的内置本地图像服务,用于创建自定义图像服务。
以下示例重用 baseService 来创建新的图像服务:
import { baseService } from "astro/assets";
const newImageService = { getURL: baseService.getURL, parseURL: baseService.parseURL, getHTMLAttributes: baseService.getHTMLAttributes, async transform(inputBuffer, transformOptions) {...}}getConfiguredImageService()
Section titled “getConfiguredImageService()”请参阅来自 astro:assets 的 getConfiguredImageService()。
getImage()
Section titled “getImage()”类型: (options: UnresolvedImageTransform, imageConfig: AstroConfig[‘image’]) => Promise<GetImageResult>
类似于来自 astro:assets 的 getImage() 函数,但有两个必需参数:一个带有 与 Image 组件相同属性的 options 对象,以及第二个用于 图像配置 的对象。
isLocalService()
Section titled “isLocalService()”类型: (service: ImageService | undefined) => boolean
检查图像服务的类型,当它是 本地服务 时返回 true。
astro/assets 类型
Section titled “astro/assets 类型”以下类型从常规资源模块导入:
import type { LocalImageProps, RemoteImageProps,} from "astro/assets";LocalImageProps
Section titled “LocalImageProps”请参阅来自 astro:assets 的 LocalImageProps。
RemoteImageProps
Section titled “RemoteImageProps”请参阅来自 astro:assets 的 RemoteImageProps。
从 astro/assets/utils 导入
Section titled “从 astro/assets/utils 导入”以下辅助函数从常规资源模块的 utils 目录导入,可用于 构建图像服务:
import { isRemoteAllowed, matchHostname, matchPathname, matchPattern, matchPort, matchProtocol, isESMImportedImage, isRemoteImage, resolveSrc, imageMetadata, emitImageMetadata, getOrigQueryParams, inferRemoteSize, propsToFilename, hashTransform, /* 以下已弃用: */ emitESMImage,} from "astro/assets/utils";isRemoteAllowed()
Section titled “isRemoteAllowed()”类型: (src: string, { domains, remotePatterns }: { domains: string[], remotePatterns: RemotePattern[] }) => boolean
astro@4.0.0
根据指定的域名和远程规则,判断一个给定的远程资源(由其源 URL 标识)是否被允许。
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: '/**', // 允许该主机名下的任何路径 }];
isRemoteAllowed(url.href, { domains, remotePatterns }); // 输出:`true`matchHostname()
Section titled “matchHostname()”类型: (url: URL, hostname?: string, allowWildcard = false) => boolean
astro@4.0.0
将给定 URL 的主机名与指定的主机名进行匹配,并为通配符规则提供可选的支持。
import { matchHostname } from 'astro/assets/utils';
const url = new URL('https://sub.example.com/path/to/resource');
matchHostname(url, 'example.com'); // 输出:`false`matchHostname(url, 'example.com', true); // 输出:`true`matchPathname()
Section titled “matchPathname()”类型: (url: URL, pathname?: string, allowWildcard = false) => boolean
astro@4.0.0
将给定 URL 的路径名与指定的规则进行匹配,并为通配符提供可选的支持。
import { matchPathname } from 'astro/assets/utils';
const testURL = new URL('https://example.com/images/photo.jpg');
matchPathname(testURL, '/images/photo.jpg'); // 输出:`true`matchPathname(testURL, '/images/'); // 输出:`false`matchPathname(testURL, '/images/*', true); // 输出:`true`matchPattern()
Section titled “matchPattern()”类型: (url: URL, remotePattern: RemotePattern) => boolean
astro@4.0.0
评估给定的 URL 是否匹配指定的远程规则(基于协议、主机名、端口以及路径名)。
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/**', // 允许 /photos/ 下的所有文件};
matchPattern(url, remotePattern); // 输出:`true`matchPort()
Section titled “matchPort()”类型: (url: URL, port?: string) => boolean
默认值: true
astro@4.0.0
检查给定 URL 的端口是否与指定的端口匹配。如果不提供端口,则返回 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'); // 输出:`true`matchPort(urlWithoutPort, '8080'); // 输出:`false`matchProtocol()
Section titled “matchProtocol()”类型: (url: URL, protocol?: string) => boolean
默认值: true
astro@4.0.0
将提供的 URL 的协议与指定的协议进行比较。如果协议匹配或未提供协议,则返回 true。
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'); // 输出:`true`matchProtocol(regularUrl, 'https'); // 输出:`false`isESMImportedImage()
Section titled “isESMImportedImage()”类型: (src: ImageMetadata | string) => boolean
astro@4.0.0
判断给定的图像来源是否为通过 ECMAScript 模块(ESM)导入的图像。
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); // 输出:`true`isESMImportedImage(filePath); // 输出:`false`isRemoteImage()
Section titled “isRemoteImage()”类型: (src: ImageMetadata | string) => boolean
astro@4.0.0
判断提供的来源是否为字符串形式的远程图像 URL。
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); // 输出:`true`isRemoteImage(localImage); // 输出:`false`resolveSrc()
Section titled “resolveSrc()”类型: (src: UnresolvedImageTransform[‘src’]) => Promise<string | ImageMetadata>
astro@4.0.0
返回图像来源。此函数确保:如果 src 是 Promise(例如:通过动态 import() 导入的模块),则会等待其解析并获取最终的 src 值;如果 src 已经是已解析的值,则直接返回。
import { resolveSrc } from 'astro/assets/utils';import localImage from "./images/photo.jpg";
const resolvedLocal = await resolveSrc(localImage);// 示例值:`{ 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");// 值:`"https://example.com/remote-img.jpg"`
const resolvedDynamic = await resolveSrc(import("./images/dynamic-image.jpg"))// 示例值:`{ src: '/@fs/home/username/dev/astro-project/src/images/dynamic-image.jpg', width: 800, height: 600, format: 'jpg' }`imageMetadata()
Section titled “imageMetadata()”类型: (data: Uint8Array, src?: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>
astro@4.0.0
从所提供的图像数据中提取其元数据,如尺寸、格式和方向。
import { imageMetadata } from 'astro/assets/utils';
const binaryImage = new Uint8Array([/* ...二进制图像数据... */]);const sourcePath = '/images/photo.jpg';
const metadata = await imageMetadata(binaryImage, sourcePath);// 示例值:// {// width: 800,// height: 600,// format: 'jpg',// orientation: undefined// }emitImageMetadata()
Section titled “emitImageMetadata()”类型: (id: string | undefined, fileEmitter?: Rollup.EmitFile) => Promise<(ImageMetadata & { contents?: Buffer }) | undefined>
astro@5.7.0
处理图像文件并生成其元数据,可选择性地输出其内容。在构建模式下,该函数通过 fileEmitter 来生成资源引用。在开发模式下,函数将其解析为本地文件 URL,并在 URL 中添加元数据相关的查询参数。
import { emitImageMetadata } from 'astro/assets/utils';
const imageId = '/images/photo.jpg';const metadata = await emitImageMetadata(imageId);// 示例值:// {// 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()
Section titled “getOrigQueryParams()”类型: (params: URLSearchParams) => Pick<ImageMetadata, ‘width’ | ‘height’ | ‘format’> | undefined
astro@4.0.0
从 URLSearchParams 对象 获取图片的 width、height 以及 format。如果其中任意一个参数缺失或无效,该函数都会返回 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);// 示例值:// {// width: 800,// height: 600,// format: 'jpg'// }inferRemoteSize()
Section titled “inferRemoteSize()”类型: (url: string) => Promise<Omit<ImageMetadata, ‘src’ | ‘fsPath’>>
astro@4.0.0
通过流式传输远程图像数据并逐步分析其内容,以推断出图片的尺寸。此方法会在获取到足够的元数据时停止。
import { inferRemoteSize } from 'astro/assets/utils';
const remoteImageUrl = 'https://example.com/image.jpg';const imageSize = await inferRemoteSize(remoteImageUrl);// 示例值:// {// width: 1920,// height: 1080,// format: 'jpg'// }propsToFilename()
Section titled “propsToFilename()”类型: (filePath: string, transform: ImageTransform, hash: string) => string
astro@4.0.0
基于图像的源路径、转换属性和唯一的哈希值,为其生成格式化的文件名。
格式化的文件名遵循以下结构:
<prefixDirname>/<baseFilename>_<hash><outputExtension>
prefixDirname:如果图像为 ESM 导入图像,则该项为原始文件路径的目录名;其他情况下,为空字符串。baseFilename:文件名的基本名称,如果文件为data:协议的 URI,则为哈希算法转换后的短名称。hash:生成唯一的哈希字符串,用以区分已转换的文件。outputExtension:从transform.format或原始文件扩展名得出的,所需输出文件扩展名。
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);// 示例值:'/images/photo_abcd1234.png'hashTransform()
Section titled “hashTransform()”类型: (transform: ImageTransform, imageService: string, propertiesToHash: string[]) => string
astro@4.0.0
基于选定的属性和指定的 imageService,将所提供的 transform 对象转换为哈希字符串。
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);// 示例值:'d41d8cd98f00b204e9800998ecf8427e'emitESMImage()
Section titled “emitESMImage()”使用 emitImageMetadata 函数进行替代。
类型: (id: string | undefined, _watchMode: boolean, experimentalSvgEnabled: boolean, fileEmitter?: Rollup.EmitFile) => Promise<(ImageMetadata & { contents?: Buffer }) | undefined>
astro@4.0.0
处理图像文件并生成其元数据及可选内容。在构建模式下,该函数使用 fileEmitter 以生成资源引用;在开发模式下,函数解析为本地文件 URL,并在 URL 中添加元数据相关的查询参数。
import { emitESMImage } from 'astro/assets/utils';
const imageId = '/images/photo.jpg';const unusedWatchMode = false; // 已弃用,闲置const unusedExperimentalSvgEnabled = false; // 仅在你使用 SVG 并希望将文件数据嵌入时,设置为 `true`const image = await emitESMImage(imageId, unusedWatchMode, unusedExperimentalSvgEnabled);// 示例值:// {// 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 类型
Section titled “astro 类型”import type { GetImageResult, ImageTransform, UnresolvedImageTransform, ImageMetadata, ImageInputFormat, ImageOutputFormat, ImageQuality, ImageQualityPreset, RemotePattern, ImageService, ExternalImageService, LocalImageService, ImageServiceConfig,} from "astro";GetImageResult
Section titled “GetImageResult”类型: object
astro@2.2.0
描述调用 getImage() 后转换的结果。
attributes
Section titled “attributes”类型: Record<string, any>
定义渲染图像所需的附加 HTML 属性(例如 width、height、style)。
options
Section titled “options”类型: ImageTransform
描述校验后的转换设置。
rawOptions
Section titled “rawOptions”类型: ImageTransform
描述原始的转换设置。
类型: string
生成图像的路径。
srcSet
Section titled “srcSet”类型: { values: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; url: string; }[]; attribute: string; }
astro@3.3.0
描述如何渲染 srcset 属性的对象。
values
Section titled “values”类型: { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>; url: string; }[]
生成值的数组,其中每个条目包含一个 URL 和一个尺寸描述符。可用于手动生成 srcset 属性的值。
attribute
Section titled “attribute”类型: string
可直接用于 srcset 属性的值。
ImageTransform
Section titled “ImageTransform”类型: object
定义图像转换服务接受的选项。包含必需的 src 属性、可选的预定义属性,以及图像服务所需的任何其他属性:
类型: ImageMetadata | string
定义 public 目录中本地图像的路径、远程图像的 URL 或导入图像的数据。
类型: number | undefined
图像的宽度。
height
Section titled “height”类型: number | undefined
图像的高度。
widths
Section titled “widths”类型: number[] | undefined
astro@3.3.0
为图像生成的宽度列表。
densities
Section titled “densities”类型: (number | `${number}x`)[] | undefined
astro@3.3.0
为图像生成的像素密度列表。
quality
Section titled “quality”类型: ImageQuality | undefined
输出图像的期望质量。
format
Section titled “format”类型: ImageOutputFormat | undefined
输出图像的期望格式。
类型: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | string | undefined
astro@5.0.0
定义 object-fit CSS 属性的允许值列表,可用任意字符串扩展。
position
Section titled “position”类型: string | undefined
astro@5.0.0
控制 object-position CSS 属性的值。
UnresolvedImageTransform
Section titled “UnresolvedImageTransform”类型: Omit<ImageTransform, “src”> & { src: ImageMetadata | string | Promise<{ default: ImageMetadata }>; inferSize?: boolean; }
表示带有转换选项的图像。包含与 ImageTransform 类型相同的属性,但有不同的 src 类型和额外的 inferSize 属性。
类型: ImageMetadata | string | Promise<{ default: ImageMetadata }>
导入的或位于 public 目录中的图像路径,或远程图像的 URL。
inferSize
Section titled “inferSize”类型: boolean
确定是否应推断图像的宽度和高度。
<Image /> 上可用的 inferSize 属性。
ImageMetadata
Section titled “ImageMetadata”类型: { src: string; width: number; height: number; format: ImageInputFormat; orientation?: number; }
astro@2.1.3
描述图像导入期间收集的数据。包含以下属性:
类型: string
图像在文件系统上的绝对路径。
类型: number
图像的宽度。
height
Section titled “height”类型: number
图像的高度。
format
Section titled “format”类型: ImageInputFormat
图像的格式。
orientation
Section titled “orientation”类型: number
astro@2.8.3
当图像元数据包含此信息时的图像方向。
ImageInputFormat
Section titled “ImageInputFormat”类型: "jpeg" | "jpg" | "png" | "tiff" | "webp" | "gif" | "svg" | "avif"
astro@2.2.0
描述导入图像支持的格式联合类型。
ImageOutputFormat
Section titled “ImageOutputFormat”类型: string | "jpeg" | "jpg" | "png" | "webp" | "svg" | "avif"
astro@2.2.0
指定输出图像的格式。可以是预定义的字面量或任意字符串。
ImageQuality
Section titled “ImageQuality”类型: ImageQualityPreset | number
astro@2.2.0
表示输出图像的感知质量,作为预定义字面量、字符串或数字的联合类型。
ImageQualityPreset
Section titled “ImageQualityPreset”类型: string | "low" | "mid" | "high" | "max"
astro@2.2.0
定义可用于控制图像质量的预设,可用任意字符串扩展。
RemotePattern
Section titled “RemotePattern”类型: { hostname?: string; pathname?: string; protocol?: string; port?: string; }
astro@5.14.2
通过四个可选属性描述远程主机:hostname、pathname、protocol 和 port。
ImageService
Section titled “ImageService”类型: ExternalImageService | LocalImageService
定义本地或外部图像服务必须提供的钩子。
ExternalImageService
Section titled “ExternalImageService”类型: object
定义外部图像转换服务必须提供的钩子。需要一个 getUrl() 钩子,并支持三个额外的钩子。
LocalImageService
Section titled “LocalImageService”类型: object
定义本地图像转换服务必须提供的钩子。需要 getUrl()、parseUrl() 和 transform() 钩子,并支持其他钩子。
ImageServiceConfig
Section titled “ImageServiceConfig”类型: { entrypoint: 'astro/assets/services/sharp' | string; config?: T; }
astro@2.3.3
描述图像服务的配置对象。包含以下属性:
entrypoint
Section titled “entrypoint”类型: 'astro/assets/services/sharp' | string
图像服务模块的包或路径。可以是 Astro 内置的 Sharp 服务或第三方服务。
config
Section titled “config”类型: Record<string, any>
传递给图像服务的配置对象。其形状取决于所使用的特定服务。
Reference