图片服务 API
astro:assets
旨在让任何图片优化服务都能轻松地在 Astro 之上构建服务。
¥astro:assets
was designed to make it easy for any image optimization service to build a service on top of Astro.
什么是图片服务?
标题部分 什么是图片服务?¥What is an Image Service?
Astro 提供两种类型的图片服务:本地和外部。
¥Astro provides two types of image services: Local and External.
-
本地服务在静态站点构建时直接处理图片转换,或在开发模式和按需渲染的运行时处理图片转换。这些通常是 Sharp、ImageMagick 或 Squoosh 等库的封装。在开发模式和按需渲染的生产路由中,本地服务使用 API 端点进行转换。
-
外部服务指向 URL,可以添加对 Cloudinary、Vercel 或任何符合 RIAPI 的服务器等服务的支持。
使用图片服务 API 进行构建
标题部分 使用图片服务 API 进行构建¥Building using the Image Services API
服务定义采用具有各种所需方法 (“hooks”) 的导出默认对象的形式。
¥Service definitions take the shape of an exported default object with various required methods (“hooks”).
外部服务提供指向输出 <img>
标记的 src
的 getURL()
。
¥External services provide a getURL()
that points to the src
of the output <img>
tag.
本地服务提供 transform()
方法来对图片执行转换,以及 getURL()
和 parseURL()
方法,用于在开发模式和按需渲染时使用端点。
¥Local services provide a transform()
method to perform transformations on your image, and getURL()
and parseURL()
methods to use an endpoint for dev mode and when rendered on demand.
两种类型的服务都可以提供 getHTMLAttributes()
来确定输出 <img>
和 validateOptions()
的其他属性,以验证和增强传递的选项。
¥Both types of services can provide getHTMLAttributes()
to determine the other attributes of the output <img>
and validateOptions()
to validate and augment the passed options.
外部服务
标题部分 外部服务¥External Services
外部服务指向要用作最终 <img>
标记的 src
属性的远程 URL。该远程 URL 负责下载、转换和返回图片。
¥An external service points to a remote URL to be used as the src
attribute of the final <img>
tag. This remote URL is responsible for downloading, transforming, and returning the image.
import type { ExternalImageService, ImageTransform, AstroConfig } from "astro";
const service: ExternalImageService = { validateOptions(options: ImageTransform, imageConfig: AstroConfig['image']) { const serviceConfig = imageConfig.service.config;
// Enforce the user set max width. if (options.width > serviceConfig.maxWidth) { console.warn(`Image width ${options.width} exceeds max width ${serviceConfig.maxWidth}. Falling back to max width.`); options.width = serviceConfig.maxWidth; }
return options; }, getURL(options, imageConfig) { return `https://mysupercdn.com/${options.src}?q=${options.quality}&w=${options.width}&h=${options.height}`; }, getHTMLAttributes(options, imageConfig) { const { src, format, quality, ...attributes } = options; return { ...attributes, loading: options.loading ?? 'lazy', decoding: options.decoding ?? 'async', }; }};
export default service;
本地服务
标题部分 本地服务¥Local Services
要创建你自己的本地服务,你可以指向 内置端点 (/_image
),也可以另外创建你自己的可以调用服务方法的端点。
¥To create your own local service, you can point to the built-in endpoint (/_image
), or you can additionally create your own endpoint that can call the service’s methods.
import type { LocalImageService, AstroConfig } from "astro";
const service: LocalImageService = { getURL(options: ImageTransform, imageConfig: AstroConfig['image']) { const searchParams = new URLSearchParams(); searchParams.append('href', typeof options.src === "string" ? options.src : options.src.src); options.width && searchParams.append('w', options.width.toString()); options.height && searchParams.append('h', options.height.toString()); options.quality && searchParams.append('q', options.quality.toString()); options.format && searchParams.append('f', options.format); return `/my_custom_endpoint_that_transforms_images?${searchParams}`; // Or use the built-in endpoint, which will call your parseURL and transform functions: // return `/_image?${searchParams}`; }, parseURL(url: URL, imageConfig) { return { src: params.get('href')!, width: params.has('w') ? parseInt(params.get('w')!) : undefined, height: params.has('h') ? parseInt(params.get('h')!) : undefined, format: params.get('f'), quality: params.get('q'), }; }, transform(buffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig): { data: Uint8Array, format: OutputFormat } { const { buffer } = mySuperLibraryThatEncodesImages(options); return { data: buffer, format: options.format, }; }, getHTMLAttributes(options, imageConfig) { let targetWidth = options.width; let targetHeight = options.height; if (typeof options.src === "object") { const aspectRatio = options.src.width / options.src.height;
if (targetHeight && !targetWidth) { targetWidth = Math.round(targetHeight * aspectRatio); } else if (targetWidth && !targetHeight) { targetHeight = Math.round(targetWidth / aspectRatio); } }
const { src, width, height, format, quality, ...attributes } = options;
return { ...attributes, width: targetWidth, height: targetHeight, loading: attributes.loading ?? 'lazy', decoding: attributes.decoding ?? 'async', }; }, propertiesToHash: ['src', 'width', 'height', 'format', 'quality'],};export default service;
在静态站点和预渲染路由的构建时,<Image />
和 getImage(options)
都会调用 transform()
函数。它们分别通过组件属性或 options
参数传递选项。转换后的图片将构建到 dist/_astro
文件夹中。它们的文件名将包含传递给 propertiesToHash
的属性的哈希值。此属性是可选的,默认为 ['src', 'width', 'height', 'format', 'quality']
。如果你的自定义图片服务有更多更改生成图片的选项,请将这些选项添加到数组中。
¥At build time for static sites and pre-rendered routes, both <Image />
and getImage(options)
call the transform()
function. They pass options either through component attributes or an options
argument, respectively. The transformed images will be built to a dist/_astro
folder. Their file names will contain a hash of the properties passed to propertiesToHash
. This property is optional and will default to ['src', 'width', 'height', 'format', 'quality']
. If your custom image service has more options that change the generated images, add these to the array.
在开发模式下,当使用适配器按需渲染时,Astro 无法提前知道哪些图片需要优化。Astro 使用 GET 端点(默认为 /_image
)在运行时处理图片。<Image />
和 getImage()
将其选项传递给 getURL()
,后者将返回端点 URL。然后,端点调用 parseURL()
并将结果属性传递给 transform()
。
¥In dev mode and when using an adapter to render on demand, Astro doesn’t know ahead of time which images need to be optimized. Astro uses a GET endpoint (by default, /_image
) to process the images at runtime. <Image />
and getImage()
pass their options to getURL()
, which will return the endpoint URL. Then, the endpoint calls parseURL()
and passes the resulting properties to transform()
.
获取配置图片服务和图片配置
标题部分 获取配置图片服务和图片配置¥getConfiguredImageService & imageConfig
如果你将自己的端点实现为 Astro 端点,则可以使用 getConfiguredImageService
和 imageConfig
调用服务的 parseURL
和 transform
方法并提供图片配置。
¥If you implement your own endpoint as an Astro endpoint, you can use getConfiguredImageService
and imageConfig
to call your service’s parseURL
and transform
methods and provide the image config.
要访问图片服务配置(image.service.config
),你可以使用 imageConfig.service.config
。
¥To access the image service config (image.service.config
), you can use imageConfig.service.config
.
import type { APIRoute } from "astro";import { getConfiguredImageService, imageConfig } from 'astro:assets';
export const GET: APIRoute = async ({ request }) => { const imageService = await getConfiguredImageService();
const imageTransform = imageService.parseURL(new URL(request.url), imageConfig); // ... fetch the image from imageTransform.src and store it in inputBuffer const { data, format } = await imageService.transform(inputBuffer, imageTransform, imageConfig); return new Response(data, { status: 200, headers: { 'Content-Type': mime.getType(format) || '' } } );}
查看内置端点 为完整示例。
¥See the built-in endpoint for a full example.
钩子
标题部分 钩子¥Hooks
getURL()
标题部分 getURL()本地和外部服务所需
¥Required for local and external services
getURL(options: ImageTransform, imageConfig: AstroConfig['image']): string
对于本地服务,此钩子返回生成图片的端点的 URL(用于按需渲染和开发模式)。在构建期间不使用它。getURL()
指向的本地端点可以同时调用 parseURL()
和 transform()
。
¥For local services, this hook returns the URL of the endpoint that generates your image (for on-demand rendering and in dev mode). It is unused during build. The local endpoint that getURL()
points to may call both parseURL()
and transform()
.
对于外部服务,此钩子返回图片的最终 URL。
¥For external services, this hook returns the final URL of the image.
对于这两种类型的服务,options
是用户作为 <Image />
组件的属性或作为 getImage()
的选项传递的属性。它们属于以下类型:
¥For both types of services, options
are the properties passed by the user as attributes of the <Image />
component or as options to getImage()
. They are of the following type:
export type ImageTransform = { // ESM imported images | remote/public image paths src: ImageMetadata | string; width?: number; height?: number; widths?: number[] | undefined; densities?: (number | `${number}x`)[] | undefined; quality?: ImageQuality; format?: OutputFormat; alt?: string; [key: string]: any;};
parseURL()
标题部分 parseURL()本地服务所需;不适用于外部服务
¥Required for local services; unavailable for external services
parseURL(url: URL, imageConfig: AstroConfig['image']): { src: string, [key: string]: any}
此钩子将 getURL()
生成的 URL 解析回具有不同属性的对象,以供 transform
使用(用于按需渲染和开发模式)。在构建期间不使用它。
¥This hook parses the generated URLs by getURL()
back into an object with the different properties to be used by transform
(for on-demand rendering and in dev mode). It is unused during build.
transform()
标题部分 transform()仅本地服务所需;不适用于外部服务
¥Required for local services only; unavailable for external services
transform(buffer: Uint8Array, options: { src: string, [key: string]: any }, imageConfig: AstroConfig['image']): { data: Uint8Array, format: OutputFormat }
该钩子转换并返回图片,并在构建过程中被调用以创建最终的资源文件。
¥This hook transforms and returns the image and is called during the build to create the final asset files.
你必须返回 format
以确保为用户提供正确的 MIME 类型以进行按需渲染和开发模式。
¥You must return a format
to ensure that the proper MIME type is served to users for on-demand rendering and development mode.
getHTMLAttributes()
标题部分 getHTMLAttributes()本地和外部服务可选
¥Optional for both local and external services
getHTMLAttributes(options: ImageTransform, imageConfig: AstroConfig['image']): Record<string, any>
该钩子根据用户传递的参数 (options
) 返回用于将图片渲染为 HTML 的所有附加属性。
¥This hook returns all additional attributes used to render the image as HTML, based on the parameters passed by the user (options
).
getSrcSet()
标题部分 getSrcSet()
Added in:
astro@3.3.0
对于本地和外部服务都是可选的。
¥Optional for both local and external services.
getSrcSet?: (options: ImageTransform, imageConfig: AstroConfig['image']): SrcSetValue[] | Promise<SrcSetValue[]>;
该钩子生成指定图片的多个变体,例如,在 <img>
或 <picture>
的 source
上生成 srcset
属性。
¥This hook generates multiple variants of the specified image, for example, to generate a srcset
attribute on an <img>
or <picture>
’s source
.
该钩子返回具有以下属性的对象数组:
¥This hook returns an array of objects with the following properties:
export type SrcSetValue = { transform: ImageTransform; descriptor?: string; attributes?: Record<string, any>;};
validateOptions()
标题部分 validateOptions()本地和外部服务可选
¥Optional for both local and external services
validateOptions(options: ImageTransform, imageConfig: AstroConfig['image']): ImageTransform
该钩子允许你验证和增强用户传递的选项。这对于设置默认选项或告诉用户需要参数非常有用。
¥This hook allows you to validate and augment the options passed by the user. This is useful for setting default options, or telling the user that a parameter is required.
查看 validateOptions()
如何在 Astro 内置服务中使用。
¥See how validateOptions()
is used in Astro built-in services.
用户配置
标题部分 用户配置¥User configuration
配置要在 astro.config.mjs
中使用的图片服务。配置采用以下形式:
¥Configure the image service to use in astro.config.mjs
. The config takes the following form:
import { defineConfig } from "astro/config";
export default defineConfig({ image: { service: { entrypoint: "your-entrypoint", // 'astro/assets/services/sharp' | string, config: { // ... service-specific config. Optional. } } },});
实用程序
标题部分 实用程序¥Utilities
Astro 公开了许多辅助函数,可用于开发自定义图片服务。可以从 astro/assets/utils
导入这些实用程序:
¥Astro exposes a number of helper functions that can be used to develop a custom image service. These utilities can be imported from astro/assets/utils
:
import { isRemoteAllowed, matchHostname, matchPathname, matchPattern, matchPort, matchProtocol, isESMImportedImage, isRemoteImage, resolveSrc, imageMetadata, emitESMImage, getOrigQueryParams, inferRemoteSize, propsToFilename, hashTransform} from "astro/assets/utils";
isRemoteAllowed()
标题部分 isRemoteAllowed()类型:(src: string, { domains, remotePatterns }: {domains: string[], remotePatterns: RemotePattern[] }): boolean
¥Type: (src: string, { domains, remotePatterns }: {domains: string[], remotePatterns: RemotePattern[] }): boolean
astro@4.0.0
根据指定的域和远程模式确定是否允许给定的远程资源(由其源 URL 标识)。
¥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 testImageURL = '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];
const url = new URL(testImageURL);const isAllowed = isRemoteAllowed(url.href, { domains, remotePatterns });
console.log(`Is the remote image allowed? ${isAllowed}`);
matchHostname()
标题部分 matchHostname()类型:(url: URL, hostname?: string, allowWildcard = false): boolean
¥Type: (url: URL, hostname?: string, allowWildcard = false): boolean
astro@4.0.0
将给定 URL 的主机名与指定的主机名进行匹配,并可选地支持通配符模式。
¥Matches a given URL’s hostname against a specified hostname, with optional support for wildcard patterns.
import { matchHostname } from 'astro/assets/utils';
const testURL = new URL('https://sub.example.com/path/to/resource');
// Example usage of matchHostnameconst hostnameToMatch = 'example.com';
// Match without wildcardconst isMatchWithoutWildcard = matchHostname(testURL, hostnameToMatch);console.log(`Does the hostname match without wildcard? ${isMatchWithoutWildcard}`); // Output: false
// Match with wildcardconst isMatchWithWildcard = matchHostname(testURL, hostnameToMatch, true);console.log(`Does the hostname match with wildcard? ${isMatchWithWildcard}`); // Output: true
matchPathname()
标题部分 matchPathname()类型:(url: URL, pathname?: string, allowWildcard = false): boolean
¥Type: (url: URL, pathname?: string, allowWildcard = false): boolean
astro@4.0.0
将给定 URL 的路径名与指定模式进行匹配,并可选择支持通配符。
¥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');
// Example pathname to matchconst pathnameToMatch = '/images/photo.jpg';
// Match without wildcardconst isMatchWithoutWildcard = matchPathname(testURL, pathnameToMatch);console.log(`Does the pathname match without wildcard? ${isMatchWithoutWildcard}`); // Output: true
// Match with wildcardconst wildcardPathname = '/images/*';const isMatchWithWildcard = matchPathname(testURL, wildcardPathname, true);console.log(`Does the pathname match with wildcard? ${isMatchWithWildcard}`); // Output: true
matchPattern()
标题部分 matchPattern()类型:(url: URL, remotePattern: RemotePattern): boolean
¥Type: (url: URL, remotePattern: RemotePattern): boolean
astro@4.0.0
根据协议、主机名、端口和路径名评估给定的 URL 是否与指定的远程模式匹配。
¥Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname.
import { matchPattern } from 'astro/assets/utils';
const testURL = new URL('https://images.example.com/photos/test.jpg');
// Define a remote pattern to match the URLconst remotePattern = { protocol: 'https', hostname: 'images.example.com', pathname: '/photos/**', // Wildcard to allow all files under /photos/ port: '', // Optional: Match any port or leave empty for default};
// Check if the URL matches the remote patternconst isPatternMatched = matchPattern(testURL, remotePattern);
console.log(`Does the URL match the remote pattern? ${isPatternMatched}`); // Output: true
matchPort()
标题部分 matchPort()类型:(url: URL, port?: string): boolean
¥Type: (url: URL, port?: string): boolean
astro@4.0.0
检查给定 URL 的端口是否与指定端口匹配。如果没有提供端口,则返回 true
。
¥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 testURL1 = new URL('https://example.com:8080/resource');const testURL2 = new URL('https://example.com/resource');
// Example usage of matchPortconst portToMatch = '8080';
// Match a URL with a port specifiedconst isPortMatch1 = matchPort(testURL1, portToMatch);console.log(`Does the port match? ${isPortMatch1}`); // Output: true
// Match a URL without a port specified (default port will be assumed)const isPortMatch2 = matchPort(testURL2, portToMatch);console.log(`Does the port match? ${isPortMatch2}`); // Output: false
// Check a URL without explicitly providing a port (defaults to true if port is undefined)const isPortMatch3 = matchPort(testURL1);console.log(`Does the port match (no port specified)? ${isPortMatch3}`); // Output: true
matchProtocol()
标题部分 matchProtocol()类型:(url: URL, protocol?: string): boolean
¥Type: (url: URL, protocol?: string): boolean
astro@4.0.0
将提供的 URL 的协议与指定的协议进行比较。
¥Compares the protocol of the provided URL with a specified protocol.
import { matchProtocol } from 'astro/assets/utils';
const testURL1 = new URL('https://example.com/resource');const testURL2 = new URL('http://example.com/resource');
// Example usage of matchProtocolconst protocolToMatch = 'https';
// Match a URL with correct protocolconst isProtocolMatch1 = matchProtocol(testURL1, protocolToMatch);console.log(`Does the protocol match for testURL1? ${isProtocolMatch1}`); // Output: true
// Match a URL with incorrect protocolconst isProtocolMatch2 = matchProtocol(testURL2, protocolToMatch);console.log(`Does the protocol match for testURL2? ${isProtocolMatch2}`); // Output: false
// Match a URL without explicitly providing a protocol (defaults to true if protocol is undefined)const isProtocolMatch3 = matchProtocol(testURL1);console.log(`Does the protocol match (no protocol specified)? ${isProtocolMatch3}`); // Output: true
isESMImportedImage()
标题部分 isESMImportedImage()类型:(src: ImageMetadata | string): boolean
¥Type: (src: ImageMetadata | string): boolean
astro@4.0.0
确定给定的源是否是 ECMAScript 模块 (ESM) 导入的图片。
¥Determines if the given source is an ECMAScript Module (ESM) imported image.
import { isESMImportedImage } from 'astro/assets/utils';
// Example usage of isESMImportedImageconst imageMetadataExample = { src: '/images/photo.jpg', width: 800, height: 600, format: 'jpg',};
const filePathExample = '/images/photo.jpg';
// Check if the input is an ESM imported imageconst isMetadataImage = isESMImportedImage(imageMetadataExample);console.log(`Is imageMetadataExample an ESM imported image? ${isMetadataImage}`); // Output: true
const isFilePathImage = isESMImportedImage(filePathExample);console.log(`Is filePathExample an ESM imported image? ${isFilePathImage}`); // Output: false
isRemoteImage()
标题部分 isRemoteImage()类型:(src: ImageMetadata | string): boolean
¥Type: (src: ImageMetadata | string): boolean
astro@4.0.0
确定提供的源是否是字符串形式的远程图片 URL。
¥Determines if the provided source is a remote image URL in the form of a string.
import { isRemoteImage } from 'astro/assets/utils';
// Example usage of isRemoteImageconst remoteImageUrl = 'https://example.com/images/photo.jpg';const localImageMetadata = { src: '/images/photo.jpg', width: 800, height: 600, format: 'jpg',};
// Check if the input is a remote image URLconst isRemote1 = isRemoteImage(remoteImageUrl);console.log(`Is remoteImageUrl a remote image? ${isRemote1}`); // Output: true
const isRemote2 = isRemoteImage(localImageMetadata);console.log(`Is localImageMetadata a remote image? ${isRemote2}`); // Output: false
resolveSrc()
标题部分 resolveSrc()类型:(src: UnresolvedImageTransform['src']): Promise<string | ImageMetadata>
¥Type: (src: UnresolvedImageTransform['src']): Promise<string | ImageMetadata>
astro@4.0.0
返回图片源。此函数确保如果 src
是 Promise(例如,动态 import()
),则等待它并提取正确的 src
。如果 src
已经是已解析的值,则按原样返回。
¥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);// will be `{ src: '/images/photo.jpg', width: 800, height: 600, format: 'jpg' }`
const resolvedRemote = await resolveSrc("https://example.com/remote-img.jpg");// will be `"https://example.com/remote-img.jpg"`
const resolvedDynamic = await resolveSrc(import("./images/dynamic-image.jpg"))// will be `{ src: '/images/dynamic-image.jpg', width: 800, height: 600, format: 'jpg' }`
imageMetadata()
标题部分 imageMetadata()类型:(data: Uint8Array, src?: string): Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>
¥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';
async function extractImageMetadata() { // Example image data (Uint8Array) const exampleImageData = new Uint8Array([/* ...binary image data... */]);
// Optional source path (useful for debugging or additional metadata context) const sourcePath = '/images/photo.jpg';
try { // Extract metadata from the image data const metadata = await imageMetadata(exampleImageData, sourcePath);
console.log('Extracted Image Metadata:', metadata); // Example output: // { // width: 800, // height: 600, // format: 'jpg', // orientation: undefined // } } catch (error) { console.error('Failed to extract metadata from image:', error); }}
await extractImageMetadata();
emitESMImage()
标题部分 emitESMImage()类型:(id: string | undefined, _watchMode: boolean, experimentalSvgEnabled: boolean, fileEmitter?: FileEmitter): Promise<ImageMetadataWithContents | undefined>
¥Type: (id: string | undefined, _watchMode: boolean, experimentalSvgEnabled: boolean, fileEmitter?: FileEmitter): Promise<ImageMetadataWithContents | undefined>
astro@4.0.0
处理图片文件并发出其元数据和可选的内容。在构建模式下,该函数使用 fileEmitter
生成资源引用。在开发模式下,它解析为带有元数据查询参数的本地文件 URL。
¥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, unusedconst unusedExperimentalSvgEnabled = false; // Set to `true` only if you are using SVG and want the file data to be embedded
try { const result = await emitESMImage(imageId, unusedWatchMode, unusedExperimentalSvgEnabled); if (result) { console.log('Image metadata with contents:', result); // Example output: // { // width: 800, // height: 600, // format: 'jpg', // contents: Uint8Array([...]) // } } else { console.log('No metadata was emitted for this image.'); }} catch (error) { console.error('Failed to emit ESM image:', error);}
getOrigQueryParams()
标题部分 getOrigQueryParams()类型:(params: URLSearchParams): Pick<ImageMetadata, 'width' | 'height' | 'format'> | undefined
¥Type: (params: URLSearchParams): Pick<ImageMetadata, 'width' | 'height' | 'format'> | undefined
astro@4.0.0
从 URLSearchParams
对象 中检索图片的 width
、height
和 format
。如果这些参数中的任何一个缺失或无效,该函数将返回 undefined
。
¥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 queryParams = url.searchParams;
// Extract the original query parametersconst origParams = getOrigQueryParams(queryParams);
if (origParams) { console.log('Original query parameters:', origParams); // Example output: // { // width: 800, // height: 600, // format: 'jpg' // }} else { console.log('Failed to extract original query parameters.');}
inferRemoteSize()
标题部分 inferRemoteSize()类型:(url: string): Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>
¥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';
async function getRemoteImageSize() { const remoteImageUrl = 'https://example.com/image.jpg';
try { // Infer remote image size from the URL const imageSize = await inferRemoteSize(remoteImageUrl);
console.log('Inferred remote image size:', imageSize); // Example output: // { // width: 1920, // height: 1080, // format: 'jpg' // } } catch (error) { console.error('Failed to infer the size of the remote image:', error); }}
await getRemoteImageSize();
propsToFilename()
标题部分 propsToFilename()类型:(filePath: string, transform: ImageTransform, hash: string): string
¥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
:如果图片是 ESM 导入的图片,则这是原始文件路径的目录名称;否则,它将是一个空字符串。 -
baseFilename
:文件的基本名称或散列短名称(如果文件是data:
URI)。 -
hash
:生成一个唯一的哈希字符串来区分转换后的文件。 -
outputExtension
:从transform.format
或原始文件扩展名派生的所需输出文件扩展名。
import { propsToFilename } from 'astro/assets/utils';
function generateTransformedFilename() { const filePath = '/images/photo.jpg'; const transform = { format: 'png', src: '/images/photo.jpg' }; const hash = 'abcd1234';
// Generate the transformed filename based on the file path, transformation, and hash const filename = propsToFilename(filePath, transform, hash);
console.log('Generated transformed filename:', filename); // Example output: '/images/photo_abcd1234.png'}
generateTransformedFilename();
hashTransform()
标题部分 hashTransform()类型:(transform: ImageTransform, imageService: string, propertiesToHash: string[]): string
¥Type: (transform: ImageTransform, imageService: string, propertiesToHash: string[]): string
astro@4.0.0
根据所选属性和指定的 imageService
将提供的 transform
对象转换为哈希字符串。
¥Transforms the provided transform
object into a hash string based on selected properties and the specified imageService
.
import { hashTransform } from 'astro/assets/utils';
function generateTransformHash() { const transform = { width: 800, height: 600, format: 'jpg', };
const imageService = 'astroImageService'; const propertiesToHash = ['width', 'height', 'format'];
// Generate the hash based on the transform, image service, and properties const hash = hashTransform(transform, imageService, propertiesToHash);
console.log('Generated transform hash:', hash); // Example output: 'd41d8cd98f00b204e9800998ecf8427e'}
generateTransformHash();