Skip to content

图片

¥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示例类型状态
srcsrc="/profile.png"字符串必需
altalt="Picture of the author"字符串必需
widthwidth={500}整数(px)*
heightheight={500}整数(px)*
fillfill={true}布尔值*
loaderloader={imageLoader}函数*
sizessizes="(max-width: 768px) 100vw, 33vw"字符串*
qualityquality={80}整数(1-100)*
prioritypriority={true}布尔值*
placeholderplaceholder="blur"字符串*
style``对象*
onLoadingCompleteonLoadingComplete={img => done())}函数已弃用
onLoadonLoad={event => done())}函数*
onErroronError(event => fail()}函数*
loadingloading="lazy"字符串*
blurDataURLblurDataURL="data:image/jpeg..."字符串*
overrideSrcoverrideSrc="/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.

widthheight

¥width and height

widthheight 属性表示 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.

你必须同时设置 widthheight 属性,除非:

¥You must set both width and height properties unless:

如果高度和宽度未知,我们建议使用 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 uses position: "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.

了解更多关于 positionobject-fit 的信息。

¥Learn more about position and object-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 prop

  • CSS 用于使图片具有响应性

    ¥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 limited srcset (e.g. 1x, 2x), suitable for fixed-size images.

  • 使用 sizes:Next.js 会生成完整的 srcset 大小(例如 640w、750w 等),并针对响应式布局进行了优化。

    ¥With sizes: Next.js generates a full srcset (e.g. 640w, 750w, etc.), optimized for responsive layouts.

了解更多关于 web.devmdnsrcsetsizes 的信息。

¥Learn more about srcset and sizes on web.dev and mdn.

quality

1100 之间的整数,用于设置优化图片的质量。值越高,文件大小和视觉保真度就越高。较低的值会减小文件大小,但可能会影响清晰度。

¥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 set height: '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:

何时不使用它:

¥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 the blurDataURL 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

如果 srcjpgpngwebpavif 文件的静态导入,则会自动添加 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 the src 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> 生成 srcsetsrc 属性。

¥When providing the src prop to the <Image> component, both the srcset and src attributes are generated automatically for the resulting <img>.

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

html
<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 在构建过程中无法访问远程文件,因此你需要手动提供 widthheight 和可选的 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.

widthheight 属性用于推断图片的正确纵横比,并避免图片加载时布局偏移。widthheight 不确定图片文件的渲染大小。

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

css
.imgDark {
  display: none;
}

@media (prefers-color-scheme: dark) {
  .imgLight {
    display: none;
  }
  .imgDark {
    display: unset;
  }
}
tsx
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" 的默认行为确保只加载正确的图片。你不能使用 priorityloading="eager",因为这会导致两个图片都加载。相反,你可以使用 fetchPriority="high"

¥Good to know: The default behavior of loading="lazy" ensures that only the correct image is loaded. You cannot use priority or loading="eager" because that would cause both images to load. Instead, you can use fetchPriority="high".

尝试一下:

¥Try it out:

艺术指导

¥Art direction

如果你想在移动设备和桌面上显示不同的图片(有时称为 艺术指导),你可以向 getImageProps() 提供不同的 srcwidthheightquality 属性。

¥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.0remotePatterns 增加了对 URL 对象数组的支持。
v15.0.0contentDispositionType 配置默认值已更改为 attachment
v14.2.23已添加 qualities 配置。
v14.2.15decoding 属性已添加,localPatterns 配置已添加。
v14.2.14remotePatterns.search 属性已添加。
v14.2.0overrideSrc 属性已添加。
v14.1.0getImageProps() 已稳定。
v14.0.0onLoadingComplete 属性和 domains 配置已弃用。
v13.4.14placeholder 属性支持 data:/image...
v13.2.0已添加 contentDispositionType 配置。
v13.0.6ref 属性已添加。
v13.0.0next/image 导入已重命名为 next/legacy/imagenext/future/image 导入已重命名为 next/image代码模式可用 可以安全、自动地重命名你的导入。<span> 封装器已删除。layoutobjectFitobjectPositionlazyBoundarylazyRoot 属性已删除。alt 是必需的。onLoadingComplete 接收对 img 元素的引用。内置加载器配置已删除。
v12.3.0remotePatternsunoptimized 配置稳定。
v12.2.0添加了实验性 remotePatterns 和实验性 unoptimized 配置。layout="raw" 已删除。
v12.1.1style 属性已添加。添加了对 layout="raw" 的实验性支持。
v12.1.0已添加 dangerouslyAllowSVGcontentSecurityPolicy 配置。
v12.0.9lazyRoot 属性已添加。
v12.0.0formats 配置已添加。
AVIF 支持已添加。
封装器 <div> 更改为 <span>
v11.1.0已添加 onLoadingCompletelazyBoundary 属性。
v11.0.0src 属性支持静态导入。
placeholder 属性已添加。
blurDataURL 属性已添加。
v10.0.5loader 属性已添加。
v10.0.1layout 属性已添加。
v10.0.0next/image 已引入。