Skip to content

图片

Astro 为你提供了多种在站点上使用图片的方法,无论它们是存储在项目本地、从外部 URL 链接还是在 CMS 或 CDN 中管理!

¥Astro provides several ways for you to use images on your site, whether they are stored locally inside your project, linked to from an external URL, or managed in a CMS or CDN!

¥Where to store images

¥src/ vs public/

我们建议尽可能将本地图片保留在 src/ 中,以便 Astro 可以对其进行转换、优化和打包。/public 目录中的文件始终按原样提供或复制到构建文件夹中,不进行任何处理。

¥We recommend that local images are kept in src/ when possible so that Astro can transform, optimize and bundle them. Files in the /public directory are always served or copied into the build folder as-is, with no processing.

你存储在 src/ 中的本地图片可供项目中的所有文件使用:.astro.md.mdx.mdoc 等 UI 框架。图片可以存储在任何文件夹中,包括与内容一起存储。

¥Your local images stored in src/ can be used by all files in your project: .astro, .md, .mdx, .mdoc, and other UI frameworks. Images can be stored in any folder, including alongside your content.

如果你想避免任何处理或拥有指向图片的直接公共链接,请将图片存储在 public/ 文件夹中。

¥Store your images in the public/ folder if you want to avoid any processing or to have a direct public link to them.

¥Remote images

你还可以选择将图片远程存储在内容管理系统 (CMS) 或数字资源管理 (DAM) 平台中。

¥You can also choose to store your images remotely, in a content management system (CMS) or digital asset management (DAM) platform.

为了在处理外部源时提供额外保护,远程图片将仅从配置中指定的 授权图片来源 进行处理。但是,可以显示任何远程图片。

¥For extra protection when dealing with external sources, remote images will only be processed from authorized image sources specified in your configuration. However, any remote images can be displayed.

Astro 可以使用 API 远程获取你的数据或从完整 URL 路径显示图片。有关集成公共服务的示例,请参阅我们的 内容管理系统指南

¥Astro can fetch your data remotely using APIs or display images from their full URL path. See our CMS guides for examples of integrating common services.

¥Images in .astro files

.astro 文件中,必须将本地图片导入文件才能使用。远程和 public/ 图片不需要导入。

¥In .astro files, local images must be imported into the file in order to be used. Remote and public/ images do not require importing.

导入并使用 Astro 的内置 <Image /> 组件,以使用 astro:assets 优化图片。或者,Astro 语法支持直接编写 HTML <img> 标签,这会跳过图片处理。

¥Import and use Astro’s built-in <Image /> component for optimized images using astro:assets. Alternatively, Astro syntax supports writing an HTML <img> tag directly, which skips image processing.

src/pages/blog/my-images.astro
---
import { Image } from 'astro:assets';
import localBirdImage from '../../images/subfolder/localBirdImage.png';
---
<Image src={localBirdImage} alt="A bird sitting on a nest of eggs." />
<Image src="/images/bird-in-public-folder.jpg" alt="A bird." width="50" height="50" />
<Image src="https://example.com/remote-bird.jpg" alt="A bird." width="50" height="50" />
<img src={localBirdImage.src} alt="A bird sitting on a nest of eggs.">
<img src="/images/bird-in-public-folder.jpg" alt="A bird.">
<img src="https://example.com/remote-bird.jpg" alt="A bird.">

要从 src/ 文件夹动态导入图片,请参阅以下秘诀:

¥To dynamically import images from the src/ folder, see the following recipe:

Related recipe: 动态导入图片

使用内置的 <Image /> Astro 组件显示本地图片和 配置远程图片 的优化版本。

¥Use the built-in <Image /> Astro component to display optimized versions of your local images and configured remote images.

public/ 文件夹中的图片以及项目中未专门配置的远程图片也可以与 Image 组件一起使用,但不会被处理。

¥Images in the public/ folder, as well as remote images not specifically configured in your project, can also be used with the Image component, but will not be processed.

<Image /> 可以转换本地或授权的远程图片的尺寸、文件类型和质量,以控制显示的图片。生成的 <img> 标签包括 altloadingdecoding 属性,并推断图片尺寸以避免累积布局偏移 (CLS)。

¥<Image /> can transform a local or authorized remote image’s dimensions, file type, and quality for control over your displayed image. The resulting <img> tag includes alt, loading, and decoding attributes and infers image dimensions to avoid Cumulative Layout Shift (CLS).

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

¥Properties

¥src (required)

图片文件的 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)

使用必需的 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/ 中的图片所需)
Section titled 宽度和高度(public/ 中的图片所需)

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

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

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

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

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

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

¥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 is an optional property that can either be:

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

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

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@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");

¥Additional properties

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

¥In addition to the properties above, the <Image /> component accepts all properties accepted by the HTML <img> tag.

例如,你可以为最终的 <img> 元素提供 class

¥For example, you can provide a class to the final <img> element.

src/pages/index.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<!-- `alt` is mandatory on the Image component -->
<Image src={myImage} alt="" class="my-class" />
<!-- Output -->
<img
src="/_astro/my_image.hash.webp"
width="1600"
height="900"
decoding="async"
loading="lazy"
class="my-class"
alt=""
/>

¥Setting Default Values

目前,无法为所有 <Image /> 组件指定默认值。应在每个单独的组件上设置必需的属性。

¥Currently, there is no way to specify default values for all <Image /> components. Required attributes should be set on each individual component.

作为替代方案,你可以将这些组件封装在另一个 Astro 组件中以供重用。例如,你可以为博客文章图片创建一个组件:

¥As an alternative, you can wrap these components in another Astro component for reuse. For example, you could create a component for your blog post images:

src/components/BlogPostImage.astro
---
import { Image } from 'astro:assets';
const { src, ...attrs } = Astro.props;
---
<Image src={src} {...attrs} />
<style>
img :global(img), svg {
margin-block: 2.5rem;
border-radius: 0.75rem;
}
</style>

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>

¥Properties

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

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

用于 <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'].

用作 <img> 标记后备值的格式。

¥Format to use as a fallback value for the <img> tag.

对于静态图片,默认为 .png(如果图片是 JPG,则为 .jpg),对于动画图片,默认为 .gif,对于 SVG 文件,默认为 .svg

¥Defaults to .png for static images (or .jpg if the image is a JPG), .gif for animated images, and .svg for SVG files.

要添加到 <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>

Astro 模板语法 还支持直接写入 <img> 标签,并完全控制其最终输出。这些图片将不会被处理和优化。

¥The Astro template syntax also supports writing an <img> tag directly, with full control over its final output. These images will not be processed and optimized.

它接受所有 HTML <img> 标记属性,唯一必需的属性是 src

¥It accepts all HTML <img> tag properties, and the only required property is src.

¥Local images in src/

必须从现有 .astro 文件的相对路径导入本地图片,或者配置并使用 import alias。然后,你可以访问图片的 src 和其他属性以在 <img> 标记中使用。

¥Local images must be imported from the relative path from the existing .astro file, or configure and use an import alias. Then, you can access the image’s src and other properties to use in the <img> tag.

例如,使用图片自身的 heightwidth 属性来避免 CLS 并提高 Core Web Vitals。

¥For example, use the image’s own height and width properties to avoid CLS and improve Core Web Vitals.

src/pages/posts/post-1.astro
---
// import local images
import myDog from '../../images/pets/local-dog.jpg';
---
// access the image properties
<img src={myDog.src} width={myDog.width} height={myDog.height} alt="A barking dog." />

导入的图片资源与以下签名匹配:

¥Imported image assets match the following signature:

interface ImageMetadata {
src: string;
width: number;
height: number;
format: string;
}

¥Images in public/

对于位于 public/ 内的图片,请使用相对于公共文件夹的图片文件路径作为 src 值:

¥For images located within public/ use the image’s file path relative to the public folder as the src value:

<img src="/images/public-cat.jpg" alt="A sleeping cat." >

¥Remote images

对于远程图片,请使用图片的完整 URL 作为 src 值:

¥For remote images, use the image’s full URL as the src value:

<img src="https://example.com/remote-cat.jpg" alt="A sleeping cat." >

¥Choosing <Image /> vs <img>

<Image /> 组件优化你的图片并根据原始宽高比推断(本地图片的)宽度和高度以避免 CLS。

¥The <Image /> component optimizes your image and infers width and height (of local images) based on the original aspect ratio to avoid CLS.

当无法使用 <Image /> 组件时,请使用 HTML <img> 元素,例如:

¥Use the HTML <img> element when you cannot use the <Image /> component, for example:

  • 对于不支持的图片格式

  • 当你不希望 Astro 优化你的图片时

  • 在客户端动态访问和更改 src 属性

¥Authorizing remote images

你可以使用 image.domainsimage.remotePatterns 配置授权图片源 URL 域和图片优化模式的列表。此配置是额外的安全层,可以在显示来自外部源的图片时保护你的站点。

¥You can configure lists of authorized image source URL domains and patterns for image optimization using image.domains and image.remotePatterns. This configuration is an extra layer of safety to protect your site when showing images from an external source.

来自其他来源的远程图片不会被优化,但对这些图片使用 <Image /> 组件将防止累积布局偏移 (CLS)。

¥Remote images from other sources will not be optimized, but using the <Image /> component for these images will prevent Cumulative Layout Shift (CLS).

例如,以下配置将仅允许优化来自 astro.build 的远程图片:

¥For example, the following configuration will only allow remote images from astro.build to be optimized:

astro.config.mjs
export default defineConfig({
image: {
domains: ["astro.build"],
}
});

以下配置仅允许来自 HTTPS 主机的远程图片:

¥The following configuration will only allow remote images from HTTPS hosts:

astro.config.mjs
export default defineConfig({
image: {
remotePatterns: [{ protocol: "https" }],
}
});

使用来自 CMS 或 CDN 的图片

Section titled 使用来自 CMS 或 CDN 的图片

¥Using Images from a CMS or CDN

图片 CDN 可与所有 Astro 图片选项配合使用。使用图片的完整 URL 作为 <Image /> 组件、<img> 标签或 Markdown 表示法中的 src 属性。对于远程图片的图片优化,还有 配置你的授权域或 URL 模式

¥Image CDNs work with all Astro image options. Use an image’s full URL as the src attribute in the <Image /> component, an <img> tag, or in Markdown notation. For image optimization with remote images, also configure your authorized domains or URL patterns.

或者,CDN 可以提供自己的 SDK,以便更轻松地集成到 Astro 项目中。例如,Cloudinary 支持 Astro SDK,它允许你使用其 CldImage 组件轻松插入图片,或者支持 Node.js SDK,它可以生成 URL 以在 Node.js 环境中与 <img> 标签一起使用。

¥Alternatively, the CDN may provide its own SDKs to more easily integrate in an Astro project. For example, Cloudinary supports an Astro SDK which allows you to easily drop in images with their CldImage component or a Node.js SDK that can generate URLs to use with an <img> tag in a Node.js environment.

¥Images in Markdown files

.md 文件中使用标准 Markdown ![alt](src) 语法。此语法与 Astro 的 图片服务 API 配合使用,以优化存储在 src/ 中的本地图片。远程图片和存储在 public/ 文件夹中的图片未经过优化。

¥Use standard Markdown ![alt](src) syntax in your .md files. This syntax works with Astro’s Image Service API to optimize your local images stored in src/. Remote images and images stored in the public/ folder are not optimized.

src/pages/post-1.md
# My Markdown Page
<!-- Local image stored in src/assets/ -->
<!-- Use a relative file path or import alias -->
![A starry night sky.](../assets/stars.png)
<!-- Image stored in public/images/ -->
<!-- Use the file path relative to public/ -->
![A starry night sky.](/images/stars.png)
<!-- Remote image on another server -->
<!-- Use the full URL of the image -->
![Astro](https://example.com/images/remote-image.png)

<img> 标签不支持本地图片,并且 <Image /> 组件在 .md 文件中不可用。

¥The <img> tag is not supported for local images, and the <Image /> component is unavailable in .md files.

如果你需要对图片属性进行更多控制,我们建议使用 .mdx 文件格式,除了 Markdown 语法之外,它还允许你包含 Astro 的 <Image /> 组件或 JSX <img /> 标记。使用 MDX 集成 向 Astro 添加对 MDX 的支持。

¥If you require more control over your image attributes, we recommend using the .mdx file format, which allows you to include Astro’s <Image /> component or a JSX <img /> tag in addition to the Markdown syntax. Use the MDX integration to add support for MDX to Astro.

¥Images in MDX files

你可以通过导入组件和图片来在 .mdx 文件中使用 Astro 的 <Image /> 组件和 JSX <img /> 标签。像 .astro 文件中使用 一样使用它们。

¥You can use Astro’s <Image /> component and JSX <img /> tags in your .mdx files by importing both the component and your image. Use them just as they are used in .astro files.

此外,还支持 标准 Markdown ![alt](src) 语法,无需导入。

¥Additionally, there is support for standard Markdown ![alt](src) syntax with no import required.

src/pages/post-1.mdx
---
title: My Page title
---
import { Image } from 'astro:assets';
import rocket from '../assets/rocket.png';
# My MDX Page
// Local image stored in the the same folder
![Houston in the wild](houston.png)
// Local image stored in src/assets/
<Image src={rocket} alt="A rocketship in space." />
<img src={rocket.src} alt="A rocketship in space." />
![A rocketship in space](../assets/rocket.png)
// Image stored in public/images/
<Image src="/images/stars.png" alt="A starry night sky." />
<img src="/images/stars.png" alt="A starry night sky." />
![A starry night sky.](/images/stars.png)
// Remote image on another server
<Image src="https://example.com/images/remote-image.png" />
<img src="https://example.com/images/remote-image.png" />
![Astro](https://example.com/images/remote-image.png)

¥Images in content collections

内容集合中的图片将以与 MarkdownMDX 中相同的方式处理,具体取决于你使用的文件类型。

¥Images in content collections will be processed the same way they are in Markdown and MDX depending on which file type you are using.

此外,你可以在前言中使用相对于当前文件夹的路径为内容集合条目(例如博客文章的封面图片)声明关联图片:

¥Additionally, you can declare an associated image for a content collections entry, such as a blog post’s cover image, in your frontmatter using its path relative to the current folder:

src/content/blog/my-post.md
---
title: "My first blog post"
cover: "./firstpostcover.jpeg" # will resolve to "src/content/blog/firstblogcover.jpeg"
coverAlt: "A photograph of a sunset behind a mountain range."
---
This is a blog post

内容集合架构的 image 辅助程序允许你使用 Zod 验证图片元数据。

¥The image helper for the content collections schema lets you validate the image metadata using Zod.

src/content/config.ts
import { defineCollection, z } from "astro:content";
const blogCollection = defineCollection({
schema: ({ image }) => z.object({
title: z.string(),
cover: image().refine((img) => img.width >= 1080, {
message: "Cover image must be at least 1080 pixels wide!",
}),
coverAlt: z.string(),
}),
});
export const collections = {
blog: blogCollection,
};

图片将被导入并转换为元数据,允许你将其作为 src<Image/><img>getImage() 传递。

¥The image will be imported and transformed into metadata, allowing you to pass it as a src to <Image/>, <img>, or getImage().

下面的示例显示了一个博客索引页面,该页面根据上面的架构渲染每个博客文章的封面照片和标题:

¥The example below shows a blog index page that renders the cover photo and title of each blog post from the schema above:

src/pages/blog.astro
---
import { Image } from "astro:assets";
import { getCollection } from "astro:content";
const allBlogPosts = await getCollection("blog");
---
{
allBlogPosts.map((post) => (
<div>
<Image src={post.data.cover} alt={post.data.coverAlt} />
<h2>
<a href={"/blog/" + post.slug}>{post.data.title}</a>
</h2>
</div>
))
}

¥Images in UI framework components

在 UI 框架组件中添加图片时,使用框架自己的图片语法来渲染图片(例如 JSX 中的 <img />,Svelte 中的 <img>)。

¥When adding images in a UI framework component, use the framework’s own image syntax to render an image (e.g. <img /> in JSX, <img> in Svelte).

必须先导入本地图片才能访问其 图片属性,例如 src

¥Local images must first be imported to access their image properties such as src.

src/components/ReactImage.jsx
import stars from "../assets/stars.png";
export default function ReactImage() {
return (
<img src={stars.src} alt="A starry night sky." />
)
}
src/components/SvelteImage.svelte
<script>
import stars from '../assets/stars.png';
</script>
<img src={stars.src} alt="A starry night sky." />

¥Passing the Image component

<Image /> 组件与任何其他 Astro 组件一样,不适用于 UI 框架组件。

¥The <Image /> component, like any other Astro component, is unavailable to UI framework components.

但是,你可以将 <Image /> 生成的静态内容作为子级或使用 命名为 <slot/> 传递到 .astro 文件内的框架组件:

¥But, you can pass the static content generated by <Image /> to a framework component inside a .astro file as children or using a named <slot/>:

src/components/ImageWrapper.astro
---
import ReactComponent from './ReactComponent.jsx';
import { Image } from 'astro:assets';
import stars from '~/stars/docline.png';
---
<ReactComponent>
<Image src={stars} alt="A starry night sky." />
</ReactComponent>

使用 getImage() 生成图片

Section titled 使用 getImage() 生成图片

¥Generating images with getImage()

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: 'webp'});
---
<div style={`background-image: url(${optimizedBackground.src});`}></div>

它返回一个具有以下属性的对象:

¥It returns an object with the following properties:

{
rawOptions: {...}, // Original parameters passed
options: {...}, // Validated parameters passed
src: "...", // Path to the generated image
srcSet: {
values: [...], // Generated values for srcset, every entry has a url and a size descriptor
attribute: "", // Generated srcset attribute from the values
}
attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..)
}

¥Alt Text

并非所有用户都能以相同的方式查看图片,因此在使用图片时可访问性是一个特别重要的问题。使用 alt 属性为图片提供 描述性替代文本

¥Not all users can see images in the same way, so accessibility is an especially important concern when using images. Use the alt attribute to provide descriptive alt text for images.

此属性对于 <Image /><Picture /> 组件都是必需的。如果没有提供替代文本,将提供有用的错误消息,提醒你包含 alt 属性。

¥This attribute is required for both the <Image /> and <Picture /> components. If no alt text is provided, a helpful error message will be provided reminding you to include the alt attribute.

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

¥If the image is merely decorative (i.e. doesn’t contribute to the understanding of the page), set alt="" so that screen readers know to ignore the image.

¥Default image service

Sharpastro:assets 使用的默认影像服务。你可以使用 image.service 选项进一步配置图片服务。

¥Sharp is the default image service used for astro:assets. You can further configure the image service using the image.service option.

¥Configure Squoosh

如果你希望使用 斯库什 来转换图片,请使用以下内容更新你的配置:

¥If you would prefer to use Squoosh to transform your images, update your config with the following:

astro.config.mjs
import { defineConfig, squooshImageService } from 'astro/config';
export default defineConfig({
image: {
service: squooshImageService(),
},
});

¥Configure no-op passthrough service

如果你的 serverhybrid 模式适配器 不支持 Astro 内置的 Squoosh 和 Sharp 图片优化(例如 Deno、Cloudflare),你可以配置无操作图片服务以允许你使用 <Image /><Picture /> 组件。请注意,Astro 在这些环境中不会执行任何图片转换和处理。但是,你仍然可以享受使用 astro:assets 的其他好处,包括无累积布局偏移 (CLS)、强制的 alt 属性以及一致的创作体验。

¥If your adapter for server or hybrid mode does not support Astro’s built-in Squoosh and Sharp image optimization (e.g. Deno, Cloudflare), you can configure a no-op image service to allow you to use the <Image /> and <Picture /> components. Note that Astro does not perform any image transformation and processing in these environments. However, you can still enjoy the other benefits of using astro:assets, including no Cumulative Layout Shift (CLS), the enforced alt attribute, and a consistent authoring experience.

配置 passthroughImageService() 以避免 Squoosh 和 Sharp 图片处理:

¥Configure the passthroughImageService() to avoid both Squoosh and Sharp image processing:

astro.config.mjs
import { defineConfig, passthroughImageService } from 'astro/config';
export default defineConfig({
image: {
service: passthroughImageService()
}
});

¥Community Integrations

有多个第三方 社区形象整合 用于优化和处理 Astro 项目中的图片。

¥There are several third-party community image integrations for optimizing and working with images in your Astro project.

Astro 中文网 - 粤ICP备13048890号