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.

Astro 提供 imagepicture 组件、Markdown 图片语法 处理、SVG 组件图片生成函数 来优化和/或转换你的图片。此外,你可以默认配置 自动调整响应式图片大小,也可以在单个图片和图片组件上设置响应式属性。

¥Astro provides image and picture components, Markdown image syntax processing, SVG components, and an image generating function to optimize and/or transform your images. Additionally, you can configure automatically resizing responsive images by default, or set responsive properties on individual image and picture components.

你始终可以选择在 .astro 或 Markdown 文件中使用原生 HTML 元素的图片和 SVG 文件,或者使用适合你文件类型的标准方式(例如,使用 MDX 和 JSX 的 <img />)。但是,Astro 不会对这些图片进行任何处理或优化。

¥You can always choose to use images and SVG files using native HTML elements in .astro or Markdown files, or the standard way for your file type (e.g. <img /> in MDX and JSX). However, Astro does not perform any processing or optimization of these images.

See the full API reference for the <Image /> and <Picture /> components.

¥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 as file imports. Images can be stored in any folder, including alongside your content.

如果你想避免任何处理,请将图片存储在 public/ 文件夹中。这些图片可以作为你域名下的 URL 路径供你的项目文件使用,并允许你直接公开链接。例如,你的网站图标通常会放置在此文件夹的根目录中,以便浏览器可以识别它。

¥Store your images in the public/ folder if you want to avoid any processing. These images are available to your project files as URL paths on your domain and allow you to have a direct public link to them. For example, your site favicon will commonly be placed in the root of this folder where browsers can identify it.

¥Remote images

你还可以选择在 内容管理系统 (CMS)数字资源管理 (DAM) 平台中远程存储图片。Astro 可以使用 API 远程获取你的数据或从完整 URL 路径显示图片。

¥You can also choose to store your images remotely, in a content management system (CMS) or digital asset management (DAM) platform. Astro can fetch your data remotely using APIs or display images from their full URL path.

为了在处理外部源时获得额外的保护,Astro 的图片组件和助手函数将仅处理(例如优化、转换)来自 配置中指定的授权图片源 的图片。来自其他来源的远程图片将不经处理显示。

¥For extra protection when dealing with external sources, Astro’s image components and helper function will only process (e.g. optimize, transform) images from authorized image sources specified in your configuration. Remote images from other sources will be displayed with no processing.

¥Images in .astro files

选项:<Image /><Picture /><img><svg>、SVG 组件

¥Options: <Image />, <Picture />, <img>, <svg>, SVG components

Astro 的模板语言允许你使用 Astro <Image /> 组件渲染优化图片,并使用 Astro <Picture /> 组件生成多种尺寸和格式的图片。这两个组件也接受 响应式图片属性 以便根据容器大小调整大小并响应设备屏幕尺寸和分辨率。

¥Astro’s templating language allows you to render optimized images with the Astro <Image /> component and generate multiple sizes and formats with the Astro <Picture /> component. Both components also accept responsive image properties for resizing based on container size and responding to device screen size and resolution.

此外,你还可以在 .astro 组件中导入和使用 SVG 文件作为 Astro 组件

¥Additionally, you can import and use SVG files as Astro components in .astro components.

所有原生 HTML 标签(包括 <img><svg>)也可用于 .astro 组件。使用 HTML 标签渲染的图片 不会被处理(例如优化、转换),并将按原样复制到你的构建文件夹中。

¥All native HTML tags, including <img> and <svg>, are also available in .astro components. Images rendered with HTML tags will not be processed (e.g. optimized, transformed) and will be copied into your build folder as-is.

对于 .astro 文件中的所有图片,图片 src 属性的值由图片文件的位置决定:

¥For all images in .astro files, the value of the image src attribute is determined by the location of your image file:

  • 来自项目 src/ 文件夹的本地图片使用文件相对路径的导入。

    图片和图片组件直接使用命名导入(例如 src={rocket}),而 <img> 标签使用导入的 src 对象属性(例如 src={rocket.src})。

  • 远程和 public/ 图片使用 URL 路径。

    请提供远程图片的完整 URL(例如 src="https://www.example.com/images/my-remote-image.jpg"),或你网站上与文件在 public/ 文件夹中位置对应的相对 URL 路径(例如,src="/images/my-public-image.jpg" 对应于位于 public/images/my-public-image.jpg 中的图片)。

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.">
See the full API reference for the <Image /> and <Picture /> components including required and optional properties.
Related recipe: 动态导入图片

Markdown 文件中的图片

标题部分 Markdown 文件中的图片

¥Images in Markdown files

选项:![]()<img>(包含公共或远程图片)

¥Options: ![](), <img> (with public or remote images)

.md 文件中使用标准 Markdown ![alt](src) 语法。存储在 src/ 中的本地图片和远程图片将被处理和优化。当你使用 全局配置响应式图片 时,这些图片也会是 responsive

¥Use standard Markdown ![alt](src) syntax in your .md files. Your local images stored in src/ and remote images will be processed and optimized. When you configure responsive images globally, these images will also be responsive.

存储在 public/ 文件夹中的图片从未优化过。

¥Images stored in the public/ folder are never 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)

HTML <img> 标记还可用于显示存储在 public/ 中的图片或远程图片,而无需任何图片优化或处理。但是,src 中的本地图片不支持 <img>

¥The HTML <img> tag can also be used to display images stored in public/ or remote images without any image optimization or processing. However, <img> is not supported for your local images in src.

<Image /><Picture /> 组件在 .md 文件中不可用。如果你需要更好地控制图片属性,我们建议使用 Astro 的 MDX 集成 来添加对 .mdx 文件格式的支持。MDX 允许额外的 MDX 中可用的图片选项,包括将组件与 Markdown 语法组合在一起。

¥The <Image /> and <Picture /> components are unavailable in .md files. If you require more control over your image attributes, we recommend using Astro’s MDX integration to add support for .mdx file format. MDX allows additional image options available in MDX, including combining components with Markdown syntax.

¥Images in MDX files

选项:<Image /><Picture /><img />![]()、SVG 组件

¥Options: <Image />, <Picture />, <img />, ![](), SVG components

你可以通过导入组件和图片在 .mdx 文件中使用 Astro 的 <Image /><Picture /> 组件。像 used in .astro files. The JSX <img /> tag is also supported for unprocessed images and uses the same image import as the HTML <img> tag 一样使用它们。

¥You can use Astro’s <Image /> and <Picture /> components in your .mdx files by importing both the component and your image. Use them just as they are used in .astro files. The JSX <img /> tag is also supported for unprocessed images and uses the same image import as the HTML <img> tag.

此外,还支持 标准 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)
See the full API reference for the <Image /> and <Picture /> components.

UI 框架组件中的图片

标题部分 UI 框架组件中的图片

¥Images in UI framework components

图片选项:框架自身的图片语法(例如 JSX 中的 <img />,Svelte 中的 <img>

¥Image options: the framework’s own image syntax (e.g. <img /> in JSX, <img> in Svelte)

Local images must first be imported 访问其图片属性,例如 src。然后,它们就可以像通常一样在该框架自身的图片语法中渲染:

¥Local images must first be imported to access their image properties such as src. Then, they can be rendered as you normally would in that framework’s own image syntax:

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

Astro 组件(例如 <Image /><Picture />、SVG 组件)由于 客户端岛必须仅包含其自身框架的有效代码 版本而无法在 UI 框架组件中使用。

¥Astro components (e.g. <Image />, <Picture />, SVG components) are unavailable inside UI framework components because a client island must contain only valid code for its own framework.

但是,你可以将这些组件生成的静态内容传递给 .astro 文件 作为子项 中的框架组件,或使用 命名为 <slot/>

¥But, you can pass the static content generated by these components 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>

¥Astro components for images

Astro 提供了两个内置的 Astro 图​​像组件(<Image /><Picture />),并且还允许你导入 SVG 文件并将其用作 Astro 组件。这些组件可以在任何可以导入和渲染 .astro 组件的文件中被使用。

¥Astro provides two built-in Astro components for images (<Image /> and <Picture />) and also allows you to import SVG files and use them as Astro components. These components may be used in any files that can import and render .astro components.

使用内置的 <Image /> Astro 组件显示优化版本:

¥Use the built-in <Image /> Astro component to display optimized versions of:

<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. This transformation happens at build time for prerendered pages. When your page is rendered on demand, this transformation will occur on the fly when the page is viewed. 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." />
<!-- Prerendered 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."
/>
<!-- Output rendered on demand-->
<!-- src will use an endpoint generated on demand-->
<img
src="/_image?href=%2F_astro%2Fmy_image.hash.webp&amp;w=1600&amp;h=900&amp;f=webp"
<!-- ... -->
/>

<Image /> 组件接受 几种组件属性 以及 HTML <img> 标记接受的任何属性。

¥The <Image /> component accepts several component properties as well as any attributes accepted by the HTML <img> tag.

以下示例为图片组件提供 class,该组件将应用于最终的 <img> 元素。

¥The following example provides a class to the image component which will apply 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" />
<!-- Prerendered output -->
<img
src="/_astro/my_image.hash.webp"
width="1600"
height="900"
decoding="async"
loading="lazy"
class="my-class"
alt=""
/>

Added in: astro@3.3.0

使用内置的 <Picture /> Astro 组件生成包含多种图片格式和/或尺寸的 <picture> 标签。这使得你可以指定要显示的首选文件格式,并同时提供后备格式。与 <Image /> 组件 类似,图片将在构建时处理预渲染页面。当你的页面按需渲染时,处理将在用户浏览页面时动态进行。

¥Use the built-in <Picture /> Astro component to generate a <picture> tag with multiple formats and/or sizes of your image. This allows you to specify preferred file formats to display and at the same time, provide a fallback format. Like the <Image /> component, images will be processed at build time for prerendered pages. When your page is rendered on demand, processing will occur on the fly when the page is viewed.

以下示例使用 <Picture /> 组件将本地 .png 文件转换为 Web 友好的 avifwebp 格式,以及可在需要时作为后备显示的 .png <img> 格式:

¥The following example uses the <Picture /> component to transform a local .png file into a web-friendly avif and webp format as well as the .png <img> that can be displayed as a fallback when needed:

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." />
<!-- Prerendered 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>
See details about the <Picture /> component properties in the astro:assets reference.

¥Responsive image behavior

Added in: astro@5.10.0

响应式图片是指可以进行调整以提高在不同设备上性能的图片。这些图片可以调整大小以适应其容器,并可以根据访问者的屏幕尺寸和分辨率以不同的尺寸显示。

¥Responsive images are images that adjust to improve performance across different devices. These images can resize to fit their container, and can be served in different sizes depending on your visitor’s screen size and resolution.

响应式图片属性 应用于 <Image /><Picture /> 组件后,Astro 会自动为你的图片生成所需的 srcsetsizes 值,并应用必要的 样式以确保其正确调整大小

¥With responsive image properties applied to the <Image /> or <Picture /> components, Astro will automatically generate the required srcset and sizes values for your images, and apply the necessary styles to ensure they resize correctly.

当此响应式行为是 全局配置 时,它将应用于所有图片组件以及使用 Markdown ![]() 语法 的任何本地和远程图片。

¥When this responsive behavior is configured globally, it will apply to all image components and also to any local and remote images using the Markdown ![]() syntax.

public/ 文件夹中的图片从未优化过,也不支持响应式图片。

¥Images in your public/ folder are never optimized, and responsive images are not supported.

为响应式图片生成 HTML 输出

标题部分 为响应式图片生成 HTML 输出

¥Generated HTML output for responsive images

设置布局时(默认或在单个组件上),图片会根据图片的尺寸和布局类型自动生成 srcsetsizes 属性。具有 constrainedfull-width 布局的图片将应用样式以确保它们根据其容器调整大小。

¥When a layout is set, either by default or on an individual component, images have automatically generated srcset and sizes attributes based on the image’s dimensions and the layout type. Images with constrained and full-width layouts will have styles applied to ensure they resize according to their container.

src/components/MyComponent.astro
---
import { Image } from 'astro:assets';
import myImage from '../assets/my_image.png';
---
<Image src={myImage} alt="A description of my image." layout='constrained' width={800} height={600} />

<Image /> 组件将在预渲染页面上生成以下 HTML 输出:

¥This <Image /> component will generate the following HTML output on a prerendered page:

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

¥Responsive image styles

设置 image.responsiveStyles: true 会应用少量全局样式,以确保图片正确调整大小。在大多数情况下,你需要默认启用这些;如果不添加其他样式,你的图片将无法响应。

¥Setting image.responsiveStyles: true applies a small number of global styles to ensure that your images resize correctly. In most cases, you will want to enable these as a default; your images will not be responsive without additional styles.

但是,如果你希望自己处理响应式图片样式,或者需要 使用 Tailwind 4 时覆盖这些默认值,请保留默认的 false 值。

¥However, if you prefer to handle responsive image styling yourself, or need to override these defaults when using Tailwind 4, leave the default false value configured.

Astro 应用的全局样式将取决于布局类型,旨在为生成的 srcsetsizes 属性生成最佳效果。这些是默认样式:

¥The global styles applied by Astro will depend on the layout type, and are designed to produce the best result for the generated srcset and sizes attributes. These are the default styles:

Responsive Image Styles
: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%;
}

样式使用 :where() 伪类,其 specificity 为 0,这意味着你可以轻松用自己的样式覆盖它。任何 CSS 选择器的优先级都高于 :where(),因此你可以通过添加自己的样式来覆盖样式,从而轻松定位到图片。

¥The styles use the :where() pseudo-class, which has a specificity of 0, meaning that it is easy to override with your own styles. Any CSS selector will have a higher specificity than :where(), so you can easily override the styles by adding your own styles to target the image.

你可以通过在 <Image /><Picture /> 组件上设置 fitposition 属性,为每个图片覆盖 object-fitobject-position 样式。

¥You can override the object-fit and object-position styles on a per-image basis by setting the fit and position props on the <Image /> or <Picture /> component.

使用 Tailwind 4 的响应式图片

标题部分 使用 Tailwind 4 的响应式图片

¥Responsive images with Tailwind 4

Tailwind 4 与 Astro 的默认响应式样式兼容。但是,Tailwind 使用 级联层,这意味着它的规则的特异性始终低于不使用图层的规则,包括 Astro 的响应式样式。因此,Astro 的样式将优先于 Tailwind 的样式。要使用 Tailwind 规则代替 Astro 的默认样式,请勿启用 Astro 的默认响应式样式

¥Tailwind 4 is compatible with Astro’s default responsive styles. However, Tailwind uses cascade layers, meaning that its rules are always lower specificity than rules that don’t use layers, including Astro’s responsive styles. Therefore, Astro’s styling will take precedence over Tailwind styling. To use Tailwind rules instead of Astro’s default styling, do not enable Astro’s default responsive styles.

¥SVG components

Added in: astro@5.7.0

Astro 允许你导入 SVG 文件并将其用作 Astro 组件。Astro 将把 SVG 内容内联到你的 HTML 输出中。

¥Astro allows you to import SVG files and use them as Astro components. Astro will inline the SVG content into your HTML output.

参考任何本地 .svg 文件的默认导入。由于此导入被视为 Astro 组件,因此你必须使用与 使用动态标签 相同的约定(例如大写)。

¥Reference the default import of any local .svg file. Since this import is treated as an Astro component, you must use the same conventions (e.g. capitalization) as when using dynamic tags.

src/components/MyAstroComponent.astro
---
import Logo from './path/to/svg/file.svg';
---
<Logo />

你的 SVG 组件(如 <Image /> 或任何其他 Astro 组件)在 UI 框架组件中不可用,但可以在 .astro 组件内使用 传递给框架组件

¥Your SVG component, like <Image /> or any other Astro component, is unavailable inside UI framework components, but can be passed to a framework component inside a .astro component.

¥SVG component attributes

你可以传递诸如 widthheightfillstroke 之类的属性,以及 原生 <svg> 元素 接受的任何其他属性。这些属性将自动应用于底层 <svg> 元素。如果原始 .svg 文件中存在属性并传递给组件,则传递给组件的值将覆盖原始值。

¥You can pass props such as width, height, fill, stroke, and any other attribute accepted by the native <svg> element. These attributes will automatically be applied to the underlying <svg> element. If a property is present in the original .svg file and is passed to the component, the value passed to the component will override the original value.

src/components/MyAstroComponent.astro
---
import Logo from '../assets/logo.svg';
---
<Logo width={64} height={64} fill="currentColor" />

创建自定义图片组件

标题部分 创建自定义图片组件

¥Creating custom image components

你可以通过将 <Image /><Picture/> 组件封装在另一个 Astro 组件中来创建自定义的可重用图片组件。这使得你只需设置一次默认属性和样式。

¥You can create a custom, reusable image component by wrapping the <Image /> or <Picture/> component in another Astro component. This allows you to set default attributes and styles only once.

例如,你可以为博客文章图片创建一个组件,该组件接收属性作为 props 并将一致的样式应用于每个图片:

¥For example, you could create a component for your blog post images that receives attributes as props and applies consistent styles to each image:

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

使用 HTML <img> 标签显示未处理的图片

标题部分 使用 HTML &lt;img&gt; 标签显示未处理的图片

¥Display unprocessed images with the HTML <img> tag

Astro 模板语法 还支持直接写入 <img> 标签,并完全控制其最终输出。这些图片将不会被处理和优化。它接受所有 HTML <img> 标记属性,唯一必需的属性是 src。但是,强烈建议包含 用于可访问性的 alt 属性

¥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. It accepts all HTML <img> tag properties, and the only required property is src. However, it is strongly recommended to include the alt property for accessibility.

¥images in src/

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

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

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

¥Imported image assets match the following signature:

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

以下示例使用图片自己的 heightwidth 属性来避免累积布局偏移 (CLS) 并改进核心 Web 生命力:

¥The following example uses the image’s own height and width properties to avoid Cumulative Layout Shift (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." />

¥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。这是在尽可能的情况下在 .astro 文件中使用图片的首选方式。

¥The <Image /> component optimizes your image and infers width and height (for images it can process) based on the original aspect ratio to avoid CLS. It is the preferred way to use images in .astro files whenever possible.

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

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

  • 对于不支持的图片格式

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

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

使用来自 CMS 或 CDN 的图片

标题部分 使用来自 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.

See the full API reference for the <Image /> and <Picture /> components.

¥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" }],
}
});

¥Images in content collections

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

¥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 助手允许你验证和导入图片。

¥The image helper for the content collections schema lets you validate and import the image.

src/content.config.ts
import { defineCollection, z } from "astro:content";
const blogCollection = defineCollection({
schema: ({ image }) => z.object({
title: z.string(),
cover: image(),
coverAlt: z.string(),
}),
});
export const collections = {
blog: blogCollection,
};

图片将被导入并转换为元数据,允许你在 Astro 组件中将其作为 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() in an Astro component.

以下示例展示了一个博客索引页,它根据之前的架构渲染了每篇博文的封面照片和标题:

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

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

使用 getImage() 生成图片

标题部分 使用 getImage() 生成图片

¥Generating images with getImage()

getImage() 函数旨在生成要在其他地方使用的图片,而不是直接在 HTML 中使用,例如在 API 路由 中。当你需要 <Picture><Image> 组件当前不支持的选项时,你可以使用 getImage() 函数创建自己的自定义 <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. When you need options that the <Picture> and <Image> components do not currently support, you can use the getImage() function to create your own custom <Image /> component.

See more in the getImage() reference.

¥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 no-op passthrough service

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

¥If your adapter does not support Astro’s built-in 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() 以避免 Sharp 图片处理:

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

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

¥Asset Caching

Astro 在为本地和 来自授权来源的远程图片 构建站点期间将处理后的图片资源存储在缓存目录中。通过在构建之间保留缓存目录,可以重用已处理的资源,从而缩短构建时间并减少带宽使用。

¥Astro stores processed image assets in a cache directory during site builds for both local and remote images from authorized sources. By preserving the cache directory between builds, processed assets are reused, improving build time and bandwidth usage.

默认缓存目录是 ./node_modules/.astro,但可以使用 cacheDir 配置设置进行更改。

¥The default cache directory is ./node_modules/.astro, however this can be changed using the cacheDir configuration setting.

¥Remote Images

资源缓存中的远程图片基于 HTTP 缓存 进行管理,并尊重远程服务器返回的 Cache-Control 标头。如果 Cache-Control 标头允许,则将缓存图片,并将一直使用到它们不再是 fresh 为止。

¥Remote images in the asset cache are managed based on HTTP Caching, and respect the Cache-Control header returned by the remote server. Images are cached if the Cache-Control header allows, and will be used until they are no longer fresh.

¥Revalidation

Added in: astro@5.1.0

重新验证 通过与远程服务器检查过期的缓存图片是否仍然是最新的来减少带宽使用量和构建时间。如果服务器指示图片仍是最新的,则重新使用缓存版本,否则将重新下载图片。

¥Revalidation reduces bandwidth usage and build time by checking with the remote server whether an expired cached image is still up-to-date. If the server indicates that the image is still fresh, the cached version is reused, otherwise the image is redownloaded.

重新验证要求远程服务器在其响应中发送 Last-Modified 和/或 Etag(实体标签) 标头。此功能适用于支持 If-Modified-SinceIf-None-Match 标头的远程服务器。

¥Revalidation requires that the remote server send Last-Modified and/or Etag (entity tag) headers with its responses. This feature is available for remote servers that support the If-Modified-Since and If-None-Match headers.

¥Community Integrations

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

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

Astro v5.10 中文网 - 粤ICP备13048890号