图片
¥Image
Next.js 图片组件扩展了 HTML <img>
元素,用于自动图片优化。
¥The Next.js Image component extends the HTML <img>
element for automatic image optimization.
需要了解:如果你使用的是 Next.js 13 之前的版本,由于组件已重命名,因此你需要使用 next/legacy/image 文档。
¥Good to know: If you are using a version of Next.js prior to 13, you'll want to use the next/legacy/image documentation since the component was renamed.
参考
¥Reference
属性
¥Props
以下属性可用:
¥The following props are available:
Prop | 示例 | 类型 | 状态 |
---|---|---|---|
src | src="/profile.png" | 字符串 | 必需 |
alt | alt="Picture of the author" | 字符串 | 必需 |
width | width={500} | 整数(px) | * |
height | height={500} | 整数(px) | * |
fill | fill={true} | 布尔值 | * |
loader | loader={imageLoader} | 函数 | * |
sizes | sizes="(max-width: 768px) 100vw, 33vw" | 字符串 | * |
quality | quality={80} | 整数(1-100) | * |
priority | priority={true} | 布尔值 | * |
placeholder | placeholder="blur" | 字符串 | * |
style | `` | 对象 | * |
onLoadingComplete | onLoadingComplete={img => done())} | 函数 | 已弃用 |
onLoad | onLoad={event => done())} | 函数 | * |
onError | onError(event => fail()} | 函数 | * |
loading | loading="lazy" | 字符串 | * |
blurDataURL | blurDataURL="data:image/jpeg..." | 字符串 | * |
overrideSrc | overrideSrc="/seo.png" | 字符串 | * |
src
图片来源。可以是以下之一:
¥The source of the image. Can be one of the following:
内部路径字符串。
¥An internal path string.
绝对外部 URL(必须使用 remotePatterns 配置)。
¥An absolute external URL (must be configured with remotePatterns).
静态导入。
¥A static import.
alt
alt
属性用于描述屏幕阅读器和搜索引擎的图片。如果图片已被禁用或加载图片时发生错误,它也是后备文本。
¥The alt
property is used to describe the image for screen readers and search engines. It is also the fallback text if images have been disabled or an error occurs while loading the image.
它应该包含可以替换图片 不改变页面的含义 的文本。它并不是为了补充图片,也不应该重复图片上方或下方的标题中已经提供的信息。
¥It should contain text that could replace the image without changing the meaning of the page. It is not meant to supplement the image and should not repeat information that is already provided in the captions above or below the image.
如果图片是 纯粹装饰性的 或 不适合用户,则 alt
属性应为空字符串 (alt=""
)。
¥If the image is purely decorative or not intended for the user, the alt
property should be an empty string (alt=""
).
了解有关 图片无障碍指南 的更多信息。
¥Learn more about image accessibility guidelines.
width
和 height
¥width
and height
width
和 height
属性表示 intrinsic 图片的大小(以像素为单位)。此属性用于推断浏览器使用的正确宽高比,以便为图片预留空间并避免加载期间的布局偏移。它不会确定图片的渲染大小,该大小由 CSS 控制。
¥The width
and height
properties represent the intrinsic image size in pixels. This property is used to infer the correct aspect ratio used by browsers to reserve space for the image and avoid layout shift during loading. It does not determine the rendered size of the image, which is controlled by CSS.
你必须同时设置 width
和 height
属性,除非:
¥You must set both width
and height
properties unless:
图片是 静态导入
¥The image is statically imported
图片具有
fill
属性¥The image has the
fill
property
如果高度和宽度未知,我们建议使用 fill
属性。
¥If the height and width are unknown, we recommend using the fill
property.
fill
一个布尔值,使图片扩展为父元素的大小。
¥A boolean that causes the image to expand to the size of the parent element.
定位:
¥Positioning:
父元素必须分配
position: "relative"
、"fixed"
、"absolute"
。¥The parent element must assign
position: "relative"
,"fixed"
,"absolute"
.默认情况下,
<img>
元素使用position: "absolute"
。¥By default, the
<img>
element usesposition: "absolute"
.
对象适配:
¥Object Fit:
如果没有对图片应用样式,图片将拉伸以适合容器。你可以使用 objectFit
来控制裁剪和缩放。
¥If no styles are applied to the image, the image will stretch to fit the container. You can use objectFit
to control cropping and scaling.
"contain"
:图片将缩小以适应容器并保持宽高比。¥
"contain"
: The image will be scaled down to fit the container and preserve aspect ratio."cover"
:图片将填满容器并被裁剪。¥
"cover"
: The image will fill the container and be cropped.
了解更多关于
position
和object-fit
的信息。¥Learn more about
position
andobject-fit
.
loader
用于生成图片 URL 的自定义函数。该函数接收以下参数,并返回图片的 URL 字符串:
¥A custom function used to generate the image URL. The function receives the following parameters, and returns a URL string for the image:
或者,你可以使用 next.config.js
中的 loaderFile 配置来配置应用中 next/image
的每个实例,而无需传递 prop。
¥Alternatively, you can use the loaderFile configuration in next.config.js
to configure every instance of next/image
in your application, without passing a prop.
sizes
在不同的断点处定义图片的大小。浏览器使用它从生成的 srcset
中选择最合适的大小。
¥Define the sizes of the image at different breakpoints. Used by the browser to choose the most appropriate size from the generated srcset
.
sizes
应在以下情况下使用:
¥sizes
should be used when:
图片正在使用
fill
属性。¥The image is using the
fill
propCSS 用于使图片具有响应性
¥CSS is used to make the image responsive
如果缺少 sizes
,浏览器会假定图片的宽度与视口 (100vw
) 相同。这可能会导致下载不必要的大图片。
¥If sizes
is missing, the browser assumes the image will be as wide as the viewport (100vw
). This can cause unnecessarily large images to be downloaded.
此外,sizes
还会影响 srcset
的生成方式:
¥In addition, sizes
affects how srcset
is generated:
不使用
sizes
:Next.js 会生成有限的srcset
大小(例如 1x、2x),适用于固定大小的图片。¥Without
sizes
: Next.js generates a limitedsrcset
(e.g. 1x, 2x), suitable for fixed-size images.使用
sizes
:Next.js 会生成完整的srcset
大小(例如 640w、750w 等),并针对响应式布局进行了优化。¥With
sizes
: Next.js generates a fullsrcset
(e.g. 640w, 750w, etc.), optimized for responsive layouts.
quality
1
和 100
之间的整数,用于设置优化图片的质量。值越高,文件大小和视觉保真度就越高。较低的值会减小文件大小,但可能会影响清晰度。
¥An integer between 1
and 100
that sets the quality of the optimized image. Higher values increase file size and visual fidelity. Lower values reduce file size but may affect sharpness.
如果你在 next.config.js
中配置了 qualities,则该值必须与允许的条目之一匹配。
¥If you’ve configured qualities in next.config.js
, the value must match one of the allowed entries.
需要了解:如果原始图片质量已经很低,设置高质量值会增加文件大小,而不会改善外观。
¥Good to know: If the original image is already low quality, setting a high quality value will increase the file size without improving appearance.
style
允许将 CSS 样式传递给底层图片元素。
¥Allows passing CSS styles to the underlying image element.
需要了解:如果你使用
style
属性设置自定义宽度,请确保同时设置height: 'auto'
以保留图片的宽高比。¥Good to know: If you’re using the
style
prop to set a custom width, be sure to also setheight: 'auto'
to preserve the image’s aspect ratio.
priority
一个布尔值,指示是否应预加载图片。
¥A boolean that indicates if the image should be preloaded.
true
:预加载 图片。禁用延迟加载。¥
true
: Preloads the image. Disables lazy loading.false
:延迟加载图片。¥
false
: Lazy loads the image.
何时使用:
¥When to use it:
图片位于首屏。
¥The image is above the fold.
图片是 最大内容涂料 (LCP) 元素。
¥The image is the Largest Contentful Paint (LCP) element.
你希望提高页面的初始加载性能。
¥You want to improve the initial loading performance of your page.
何时不使用它:
¥When not to use it:
使用
loading
属性时(将触发警告)。¥When the
loading
prop isused (will trigger warnings).
loading
控制图片何时开始加载。
¥Controls when the image should start loading.
lazy
:延迟加载图片,直到其与视口的距离达到计算值。¥
lazy
: Defer loading the image until it reaches a calculated distance from the viewport.eager
:立即加载图片,无论其在页面中的位置如何。¥
eager
: Load the image immediately, regardless of its position in the page.
仅在需要确保图片立即加载时使用 eager
。
¥Use eager
only when you want to ensure the image is loaded immediately.
了解有关
loading
属性 的更多信息。¥Learn more about the
loading
attribute.
placeholder
指定图片加载时使用的占位符,以提高感知的加载性能。
¥Specifies a placeholder to use while the image is loading, improving the perceived loading performance.
empty
:图片加载时无需占位符。¥
empty
: No placeholder while the image is loading.blur
:使用模糊版本的图片作为占位符。必须与blurDataURL
属性一起使用。¥
blur
: Use a blurred version of the image as a placeholder. Must be used with theblurDataURL
property.data:image/...
:使用 数据网址 作为占位符。¥
data:image/...
: Uses the Data URL as the placeholder.
示例:
¥Examples:
了解有关
placeholder
属性 的更多信息。¥Learn more about the
placeholder
attribute.
blurDataURL
在图片成功加载之前用作占位符的 数据网址。可以自动设置或与 placeholder="blur"
属性一起使用。
¥A Data URL to be used as a placeholder image before the image successfully loads. Can be automatically set or used with the placeholder="blur"
property.
图片会自动放大并模糊处理,因此建议使用非常小的图片(10px 或更小)。
¥The image is automatically enlarged and blurred, so a very small image (10px or less) is recommended.
自动
¥Automatic
如果 src
是 jpg
、png
、webp
或 avif
文件的静态导入,则会自动添加 blurDataURL
- 除非图片是动画。
¥If src
is a static import of a jpg
, png
, webp
, or avif
file, blurDataURL
is added automatically—unless the image is animated.
手动设置
¥Manually set
如果图片是动态的或远程的,则必须自行提供 blurDataURL
。要生成入口点,你可以使用:
¥If the image is dynamic or remote, you must provide blurDataURL
yourself. To generate one, you can use:
较大的 blurDataURL 可能会影响性能。保持小巧简洁。
¥A large blurDataURL may hurt performance. Keep it small and simple.
示例:
¥Examples:
onLoad
图片完全加载且 placeholder 已删除后调用的回调函数。
¥A callback function that is invoked once the image is completely loaded and the placeholder has been removed.
回调函数将使用一个参数调用,该参数为包含引用底层 <img>
元素的 target
的事件。
¥The callback function will be called with one argument, the event which has a target
that references the underlying <img>
element.
onError
图片加载失败时调用的回调函数。
¥A callback function that is invoked if the image fails to load.
unoptimized
一个布尔值,指示是否应优化图片。这对于无法从优化中受益的图片很有用,例如小图片(小于 1KB)、矢量图片(SVG)或动画图片(GIF)。
¥A boolean that indicates if the image should be optimized. This is useful for images that do not benefit from optimization such as small images (less than 1KB), vector images (SVG), or animated images (GIF).
true
:源图片将按原样从src
提供,而不会改变质量、大小或格式。¥
true
: The source image will be served as-is from thesrc
instead of changing quality, size, or format.false
:源图片将被优化。¥
false
: The source image will be optimized.
从 Next.js 12.3.0 开始,可以通过使用以下配置更新 next.config.js
来将此属性分配给所有图片:
¥Since Next.js 12.3.0, this prop can be assigned to all images by updating next.config.js
with the following configuration:
overrideSrc
当将 src
属性提供给 <Image>
组件时,将自动为生成的 <img>
生成 srcset
和 src
属性。
¥When providing the src
prop to the <Image>
component, both the srcset
and src
attributes are generated automatically for the resulting <img>
.
<img
srcset="
/_next/image?url=%2Fme.jpg&w=640&q=75 1x,
/_next/image?url=%2Fme.jpg&w=828&q=75 2x
"
src="/_next/image?url=%2Fme.jpg&w=828&q=75"
/>
在某些情况下,不希望生成 src
属性,你可能希望使用 overrideSrc
prop 覆盖它。
¥In some cases, it is not desirable to have the src
attribute generated and you may wish to override it using the overrideSrc
prop.
例如,在将现有网站从 <img>
升级到 <Image>
时,你可能希望出于 SEO 目的(例如图片排名或避免重新抓取)保留相同的 src
属性。
¥For example, when upgrading an existing website from <img>
to <Image>
, you may wish to maintain the same src
attribute for SEO purposes such as image ranking or avoiding recrawl.
<img
srcset="
/_next/image?url=%2Fme.jpg&w=640&q=75 1x,
/_next/image?url=%2Fme.jpg&w=828&q=75 2x
"
src="/override.jpg"
/>
decoding
向浏览器提示是否应等待图片解码后再显示其他内容更新。
¥A hint to the browser indicating if it should wait for the image to be decoded before presenting other content updates or not.
async
:异步解码图片并允许在完成之前渲染其他内容。¥
async
: Asynchronously decode the image and allow other content to be rendered before it completes.sync
:同步解码图片以与其他内容进行原子渲染。¥
sync
: Synchronously decode the image for atomic presentation with other content.auto
:无偏好。浏览器会选择最佳方法。¥
auto
: No preference. The browser chooses the best approach.
了解有关
decoding
属性 的更多信息。¥Learn more about the
decoding
attribute.
其他属性
¥Other Props
`
使用远程 URL 的响应式图片
¥Responsive images with a remote URL
如果源图片是动态的或远程 URL,则必须提供 width 和 height 属性,以便 Next.js 计算宽高比:
¥If the source image is a dynamic or a remote URL, you must provide the width and height props so Next.js can calculate the aspect ratio:
尝试一下:
¥Try it out:
带有 fill
的响应式图片
¥Responsive image with fill
如果你不知道图片的宽高比,可以添加 fill
属性 并将 objectFit
属性设置为 cover
。这将使图片填满其父容器的整个宽度。
¥If you don't know the aspect ratio of the image, you can add the fill
prop with the objectFit
prop set to cover
. This will make the image fill the full width of its parent container.

背景图片
¥Background Image
使用 fill
属性使图片覆盖整个屏幕区域:
¥Use the fill
prop to make the image cover the entire screen area:

有关与各种样式一起使用的图片组件的示例,请参阅 图片组件演示。
¥For examples of the Image component used with the various styles, see the Image Component Demo.
远程图片
¥Remote images
要使用远程图片,src
属性应为 URL 字符串。
¥To use a remote image, the src
property should be a URL string.
由于 Next.js 在构建过程中无法访问远程文件,因此你需要手动提供 width
、height
和可选的 blurDataURL
属性。
¥Since Next.js does not have access to remote files during the build process, you'll need to provide the width
, height
and optional blurDataURL
props manually.
width
和 height
属性用于推断图片的正确纵横比,并避免图片加载时布局偏移。width
和 height
不确定图片文件的渲染大小。
¥The width
and height
attributes are used to infer the correct aspect ratio of image and avoid layout shift from the image loading in. The width
and height
do not determine the rendered size of the image file.
为了安全地允许优化图片,请在 next.config.js
中定义一个受支持的 URL 模式列表。尽可能具体,以防止恶意使用。例如,以下配置将仅允许来自特定 AWS S3 存储桶的图片:
¥To safely allow optimizing images, define a list of supported URL patterns in next.config.js
. Be as specific as possible to prevent malicious usage. For example, the following configuration will only allow images from a specific AWS S3 bucket:
主题检测
¥Theme detection
如果你想为明夜间模式显示不同的图片,你可以创建一个新组件,该组件封装两个 <Image>
组件并根据 CSS 媒体查询显示正确的组件。
¥If you want to display a different image for light and dark mode, you can create a new component that wraps two <Image>
components and reveals the correct one based on a CSS media query.
.imgDark {
display: none;
}
@media (prefers-color-scheme: dark) {
.imgLight {
display: none;
}
.imgDark {
display: unset;
}
}
import styles from './theme-image.module.css'
import Image, { ImageProps } from 'next/image'
type Props = Omit<ImageProps, 'src' | 'priority' | 'loading'> & {
srcLight: string
srcDark: string
}
const ThemeImage = (props: Props) => {
const { srcLight, srcDark, ...rest } = props
return (
<>
<Image {...rest} src={srcLight} className={styles.imgLight} />
<Image {...rest} src={srcDark} className={styles.imgDark} />
</>
)
}
需要了解:
loading="lazy"
的默认行为确保只加载正确的图片。你不能使用priority
或loading="eager"
,因为这会导致两个图片都加载。相反,你可以使用fetchPriority="high"
。¥Good to know: The default behavior of
loading="lazy"
ensures that only the correct image is loaded. You cannot usepriority
orloading="eager"
because that would cause both images to load. Instead, you can usefetchPriority="high"
.
尝试一下:
¥Try it out:
艺术指导
¥Art direction
如果你想在移动设备和桌面上显示不同的图片(有时称为 艺术指导),你可以向 getImageProps()
提供不同的 src
、width
、height
和 quality
属性。
¥If you want to display a different image for mobile and desktop, sometimes called Art Direction, you can provide different src
, width
, height
, and quality
props to getImageProps()
.
背景 CSS
¥Background CSS
你甚至可以将 srcSet
字符串转换为 image-set()
CSS 函数来优化背景图片。
¥You can even convert the srcSet
string to the image-set()
CSS function to optimize a background image.
版本历史
¥Version History
版本 | 更改 |
---|---|
v15.3.0 | remotePatterns 增加了对 URL 对象数组的支持。 |
v15.0.0 | contentDispositionType 配置默认值已更改为 attachment 。 |
v14.2.23 | 已添加 qualities 配置。 |
v14.2.15 | decoding 属性已添加,localPatterns 配置已添加。 |
v14.2.14 | remotePatterns.search 属性已添加。 |
v14.2.0 | overrideSrc 属性已添加。 |
v14.1.0 | getImageProps() 已稳定。 |
v14.0.0 | onLoadingComplete 属性和 domains 配置已弃用。 |
v13.4.14 | placeholder 属性支持 data:/image... |
v13.2.0 | 已添加 contentDispositionType 配置。 |
v13.0.6 | ref 属性已添加。 |
v13.0.0 | next/image 导入已重命名为 next/legacy/image 。next/future/image 导入已重命名为 next/image 。代码模式可用 可以安全、自动地重命名你的导入。<span> 封装器已删除。layout 、objectFit 、objectPosition 、lazyBoundary 、lazyRoot 属性已删除。alt 是必需的。onLoadingComplete 接收对 img 元素的引用。内置加载器配置已删除。 |
v12.3.0 | remotePatterns 和 unoptimized 配置稳定。 |
v12.2.0 | 添加了实验性 remotePatterns 和实验性 unoptimized 配置。layout="raw" 已删除。 |
v12.1.1 | style 属性已添加。添加了对 layout="raw" 的实验性支持。 |
v12.1.0 | 已添加 dangerouslyAllowSVG 和 contentSecurityPolicy 配置。 |
v12.0.9 | lazyRoot 属性已添加。 |
v12.0.0 | formats 配置已添加。AVIF 支持已添加。 封装器 <div> 更改为 <span> 。 |
v11.1.0 | 已添加 onLoadingComplete 和 lazyBoundary 属性。 |
v11.0.0 | src 属性支持静态导入。placeholder 属性已添加。blurDataURL 属性已添加。 |
v10.0.5 | loader 属性已添加。 |
v10.0.1 | layout 属性已添加。 |
v10.0.0 | next/image 已引入。 |