跳到内容

Image

Next.js 图像组件扩展了 HTML <img> 元素,用于自动图像优化。

app/page.js
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="/profile.png"
      width={500}
      height={500}
      alt="Picture of the author"
    />
  )
}

温馨提示:如果您使用的是 Next.js 13 之前的版本,您需要查阅 next/legacy/image 文档,因为该组件已重命名。

参考

属性

以下属性可用

属性示例类型状态
srcsrc="/profile.png"字符串必需
altalt="作者图片"字符串必需
widthwidth={500}整数 (px)-
heightheight={500}整数 (px)-
填充fill={true}布尔值-
加载器loader={imageLoader}函数-
尺寸sizes="(max-width: 768px) 100vw, 33vw"字符串-
质量quality={80}整数 (1-100)-
预加载preload={true}布尔值-
占位符placeholder="blur"字符串-
stylestyle={{objectFit: "contain"}}对象-
onLoadingCompleteonLoadingComplete={img => done())}函数已弃用
onLoadonLoad={event => done())}函数-
onErroronError(event => fail()}函数-
loadingloading="lazy"字符串-
blurDataURLblurDataURL="data:image/jpeg..."字符串-
unoptimizedunoptimized={true}布尔值-
overrideSrcoverrideSrc="/seo.png"字符串-
decodingdecoding="async"字符串-

src

图像的来源。可以是以下之一

内部路径字符串。

<Image src="/profile.png" />

绝对外部 URL(必须使用 remotePatterns 配置)。

<Image src="https://example.com/profile.png" />

静态导入。

import profile from './profile.png'
 
export default function Page() {
  return <Image src={profile} />
}

温馨提示:出于安全原因,使用默认 加载器 的图像优化 API 在获取 src 图像时不会转发请求头。如果 src 图像需要身份验证,请考虑使用 unoptimized 属性禁用图像优化。

alt

alt 属性用于为屏幕阅读器和搜索引擎描述图像。如果图像被禁用或加载图像时出错,它也是备用文本。

它应包含可以在不改变页面含义的情况下替换图像的文本。它不用于补充图像,也不应重复图像上方或下方标题中已提供的信息。

如果图像纯粹是装饰性的不供用户使用,则 alt 属性应为空字符串 (alt="")。

了解有关图像无障碍指南的更多信息。

widthheight

widthheight 属性表示图像的固有尺寸(以像素为单位)。此属性用于推断浏览器用于为图像保留空间并避免加载期间布局偏移的正确纵横比。它不决定图像的渲染尺寸,这由 CSS 控制。

<Image src="/profile.png" width={500} height={500} />

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

如果高度和宽度未知,我们建议使用 fill 属性

fill

一个布尔值,使图像扩展到父元素的大小。

<Image src="/profile.png" fill={true} />

定位:

  • 父元素必须指定 position: "relative""fixed""absolute"
  • 默认情况下,<img> 元素使用 position: "absolute"

对象适应:

如果未对图像应用样式,图像将拉伸以适应容器。您可以使用 objectFit 来控制裁剪和缩放。

  • "contain":图像将缩小以适应容器并保持纵横比。
  • "cover":图像将填充容器并被裁剪。

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

loader

用于生成图像 URL 的自定义函数。该函数接收以下参数,并返回图像的 URL 字符串

import Image from 'next/image'
 
const imageLoader = ({ src, width, quality }) => {
  return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
 
export default function Page() {
  return (
    <Image
      loader={imageLoader}
      src="me.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

或者,您可以使用 next.config.js 中的 loaderFile 配置来配置应用程序中 next/image 的每个实例,而无需传递属性。

sizes

在不同的断点定义图像的尺寸。浏览器使用它从生成的 srcset 中选择最合适的尺寸。

import Image from 'next/image'
 
export default function Page() {
  return (
    <div className="grid-element">
      <Image
        fill
        src="/example.png"
        sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
      />
    </div>
  )
}

sizes 应在以下情况下使用

  • 图像正在使用 fill 属性
  • CSS 用于使图像具有响应性

如果缺少 sizes,浏览器会假定图像将与视口一样宽 (100vw)。这可能导致下载不必要的大图像。

此外,sizes 影响 srcset 的生成方式

  • 没有 sizes:Next.js 生成有限的 srcset(例如 1x,2x),适用于固定大小的图像。
  • sizes:Next.js 生成完整的 srcset(例如 640w,750w 等),针对响应式布局进行了优化。

web.devmdn上了解有关 srcsetsizes 的更多信息。

quality

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

// Default quality is 75
<Image quality={75} />

如果您在 next.config.js 中配置了 qualities,则该值必须与允许的条目之一匹配。

温馨提示:如果原始图像质量已经很低,设置高质量值会增加文件大小,但不会改善外观。

style

允许将 CSS 样式传递给底层图像元素。

const imageStyle = {
  borderRadius: '50%',
  border: '1px solid #fff',
  width: '100px',
  height: 'auto',
}
 
export default function ProfileImage() {
  return <Image src="..." style={imageStyle} />
}

温馨提示:如果您使用 style 属性设置自定义宽度,请务必同时设置 height: 'auto' 以保持图像的纵横比。

preload

一个布尔值,指示图像是否应预加载。

// Default preload is false
<Image preload={false} />
  • true:通过在 <head> 中插入 <link>预加载图像。
  • false:不预加载图像。

何时使用它

  • 图像是最大内容绘制 (LCP)元素。
  • 图像位于首屏,通常是主视觉图。
  • 您希望在 <head> 中开始加载图像,而不是稍后在 <body> 中发现它。

何时不使用它

  • 当您有多个图像可能根据视口被视为最大内容绘制 (LCP)元素时。
  • 使用 loading 属性时。
  • 使用 fetchPriority 属性时。

在大多数情况下,您应该使用 loading="eager"fetchPriority="high" 而不是 preload

priority

从 Next.js 16 开始,priority 属性已被弃用,转而使用 preload 属性,以使行为更清晰。

loading

控制图像何时开始加载。

// Defaults to lazy
<Image loading="lazy" />
  • lazy:推迟加载图像,直到它到达视口的一定距离。
  • eager:立即加载图像,无论其在页面中的位置如何。

仅当您希望确保图像立即加载时才使用 eager

了解有关loading 属性的更多信息。

placeholder

指定图像加载时使用的占位符,从而改善感知到的加载性能。

// defaults to empty
<Image placeholder="empty" />
  • empty:图像加载时没有占位符。
  • blur:使用图像的模糊版本作为占位符。必须与 blurDataURL 属性一起使用。
  • data:image/...:使用数据 URL作为占位符。

示例

了解有关placeholder 属性的更多信息。

blurDataURL

在图像成功加载之前用作占位符图像的数据 URL。可以自动设置或与 placeholder="blur" 属性一起使用。

<Image placeholder="blur" blurDataURL="..." />

图像会自动放大和模糊,因此建议使用非常小的图像(10 像素或更小)。

自动

如果 srcjpgpngwebpavif 文件的静态导入,则会自动添加 blurDataURL,除非图像是动画的。

手动设置

如果图像是动态或远程的,您必须自行提供 blurDataURL。要生成一个,您可以使用

大的 blurDataURL 可能会影响性能。请保持其小巧简单。

示例

onLoad

图像完全加载且占位符已移除后调用的回调函数。

<Image onLoad={(e) => console.log(e.target.naturalWidth)} />

回调函数将带有一个参数调用,该参数是一个事件,其 target 引用底层 <img> 元素。

onError

如果图像加载失败,则调用的回调函数。

<Image onError={(e) => console.error(e.target.id)} />

unoptimized

一个布尔值,指示图像是否应优化。这对于不从优化中受益的图像(如小图像(小于 1KB)、矢量图像(SVG)或动画图像(GIF))很有用。

import Image from 'next/image'
 
const UnoptimizedImage = (props) => {
  // Default is false
  return <Image {...props} unoptimized />
}
  • true:源图像将按原样从 src 提供,而不是更改质量、大小或格式。
  • false:源图像将被优化。

自 Next.js 12.3.0 起,可以通过更新 next.config.js 并使用以下配置将此属性分配给所有图像

next.config.js
module.exports = {
  images: {
    unoptimized: true,
  },
}

overrideSrc

src 属性提供给 <Image> 组件时,srcsetsrc 属性都会为生成的 <img> 自动生成。

input.js
<Image src="/profile.jpg" />
output.html
<img
  srcset="
    /_next/image?url=%2Fprofile.jpg&w=640&q=75 1x,
    /_next/image?url=%2Fprofile.jpg&w=828&q=75 2x
  "
  src="/_next/image?url=%2Fprofile.jpg&w=828&q=75"
/>

在某些情况下,不希望生成 src 属性,您可能希望使用 overrideSrc 属性覆盖它。

例如,当将现有网站从 <img> 升级到 <Image> 时,您可能希望出于 SEO 目的(例如图像排名或避免重新抓取)保持相同的 src 属性。

input.js
<Image src="/profile.jpg" overrideSrc="/override.jpg" />
output.html
<img
  srcset="
    /_next/image?url=%2Fprofile.jpg&w=640&q=75 1x,
    /_next/image?url=%2Fprofile.jpg&w=828&q=75 2x
  "
  src="/override.jpg"
/>

decoding

向浏览器提示是否应在呈现其他内容更新之前等待图像解码。

// Default is async
<Image decoding="async" />
  • async:异步解码图像,并允许在完成之前呈现其他内容。
  • sync:同步解码图像,以便与其他内容原子呈现。
  • auto:无偏好。浏览器选择最佳方法。

了解有关decoding 属性的更多信息。

其他属性

<Image /> 组件上的其他属性将传递给底层 img 元素,但以下情况除外

已弃用的属性

onLoadingComplete

警告:在 Next.js 14 中已弃用,请改用 onLoad

图像完全加载且占位符已移除后调用的回调函数。

回调函数将带有一个参数调用,该参数是对底层 <img> 元素的引用。

<Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />

配置选项

您可以在 next.config.js 中配置图像组件。以下选项可用

localPatterns

在您的 next.config.js 文件中使用 localPatterns 允许优化特定本地路径中的图像,并阻止所有其他图像。

next.config.js
module.exports = {
  images: {
    localPatterns: [
      {
        pathname: '/assets/images/**',
        search: '',
      },
    ],
  },
}

上述示例将确保 next/imagesrc 属性必须以 /assets/images/ 开头,并且不能带有查询字符串。尝试优化任何其他路径将响应 400 错误请求。

温馨提示:省略 search 属性允许所有搜索参数,这可能允许恶意行为者优化您不希望优化的 URL。尝试使用特定值,例如 search: '?v=2',以确保精确匹配。

remotePatterns

在您的 next.config.js 文件中使用 remotePatterns 允许来自特定外部路径的图像,并阻止所有其他图像。这确保只有来自您帐户的外部图像可以提供。

next.config.js
module.exports = {
  images: {
    remotePatterns: [new URL('https://example.com/account123/**')],
  },
}

您还可以使用对象配置 remotePatterns

next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'example.com',
        port: '',
        pathname: '/account123/**',
        search: '',
      },
    ],
  },
}

上述示例将确保 next/imagesrc 属性必须以 https://example.com/account123/ 开头,并且不能包含查询字符串。任何其他协议、主机名、端口或不匹配的路径都将响应 400 错误请求。

通配符模式

通配符模式可用于 pathnamehostname,并具有以下语法

  • * 匹配单个路径段或子域名
  • ** 匹配末尾任意数量的路径段或开头任意数量的子域名。此语法不适用于模式中间。
next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.example.com',
        port: '',
        search: '',
      },
    ],
  },
}

这允许子域名,例如 image.example.com。查询字符串和自定义端口仍然被阻止。

温馨提示:省略 protocolportpathnamesearch 时,隐含通配符 **。不建议这样做,因为它可能允许恶意行为者优化您不希望优化的 URL。

查询字符串:

您还可以使用 search 属性限制查询字符串

next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'assets.example.com',
        search: '?v=1727111025337',
      },
    ],
  },
}

上述示例将确保 next/imagesrc 属性必须以 https://assets.example.com 开头,并且必须具有精确的查询字符串 ?v=1727111025337。任何其他协议或查询字符串都将响应 400 错误请求。

loaderFile

loaderFiles 允许您使用自定义图像优化服务而不是 Next.js。

next.config.js
module.exports = {
  images: {
    loader: 'custom',
    loaderFile: './my/image/loader.js',
  },
}

路径必须相对于项目根目录。文件必须导出返回 URL 字符串的默认函数

my/image/loader.js
export default function myImageLoader({ src, width, quality }) {
  return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}

示例

或者,您可以使用 loader 属性来配置 next/image 的每个实例。

path

如果您想更改或为图像优化 API 的默认路径添加前缀,您可以使用 path 属性。path 的默认值为 /_next/image

next.config.js
module.exports = {
  images: {
    path: '/my-prefix/_next/image',
  },
}

deviceSizes

deviceSizes 允许您指定设备宽度断点列表。当 next/image 组件使用 sizes 属性以确保为用户的设备提供正确的图像时,会使用这些宽度。

如果未提供配置,则使用以下默认值

next.config.js
module.exports = {
  images: {
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
  },
}

imageSizes

imageSizes 允许您指定图像宽度列表。这些宽度与 设备尺寸 数组连接,形成用于生成图像 srcset 的完整尺寸数组。

如果未提供配置,则使用以下默认值

next.config.js
module.exports = {
  images: {
    imageSizes: [32, 48, 64, 96, 128, 256, 384],
  },
}

imageSizes 仅用于提供 sizes 属性的图像,这表示图像小于屏幕的完整宽度。因此,imageSizes 中的所有尺寸都应小于 deviceSizes 中的最小尺寸。

qualities

qualities 允许您指定图像质量值列表。

如果未提供配置,则使用以下默认值

next.config.js
module.exports = {
  images: {
    qualities: [75],
  },
}

温馨提示:从 Next.js 16 开始,此字段是必需的,因为不受限制的访问可能允许恶意行为者优化超出您意图的更多质量。

您可以将更多图像质量添加到允许列表,例如以下内容

next.config.js
module.exports = {
  images: {
    qualities: [25, 50, 75, 100],
  },
}

在上述示例中,只允许四种质量:25、50、75 和 100。

如果 quality 属性与此数组中的值不匹配,将使用最接近的允许值。

如果直接使用与此数组中的值不匹配的质量访问 REST API,服务器将返回 400 错误请求响应。

formats

formats 允许您指定要使用的图像格式列表。

next.config.js
module.exports = {
  images: {
    // Default
    formats: ['image/webp'],
  },
}

Next.js 通过请求的 Accept 头部自动检测浏览器支持的图像格式,以确定最佳输出格式。

如果 Accept 头部匹配多个配置的格式,则使用数组中的第一个匹配项。因此,数组顺序很重要。如果没有匹配项(或源图像是动画的),它将使用原始图像的格式。

您可以启用 AVIF 支持,如果浏览器不支持 AVIF,它将回退到 src 图像的原始格式

next.config.js
module.exports = {
  images: {
    formats: ['image/avif'],
  },
}

须知:

  • 我们仍然建议在大多数用例中使用 WebP。
  • AVIF 通常编码时间长 50%,但压缩率比 WebP 小 20%。这意味着图像第一次请求时通常会较慢,但后续缓存的请求会更快。
  • 如果您使用 Proxy/CDN 在 Next.js 前面进行自托管,则必须配置 Proxy 以转发 Accept 头部。

minimumCacheTTL

minimumCacheTTL 允许您配置缓存优化图像的生存时间 (TTL)(以秒为单位)。在许多情况下,最好使用静态图像导入,它会自动哈希文件内容并使用 Cache-Control 头部 immutable 永久缓存图像。

如果未提供配置,则使用以下默认值。

next.config.js
module.exports = {
  images: {
    minimumCacheTTL: 14400, // 4 hours
  },
}

您可以增加 TTL 以减少重新验证次数并可能降低成本

next.config.js
module.exports = {
  images: {
    minimumCacheTTL: 2678400, // 31 days
  },
}

优化图像的过期时间(或者更确切地说是最大寿命)由 minimumCacheTTL 或上游图像 Cache-Control 标头(以较大者为准)定义。

如果您需要更改每个图像的缓存行为,您可以配置headers来设置上游图像(例如/some-asset.jpg,而不是/_next/image本身)上的Cache-Control标头。

目前没有机制来使缓存失效,因此最好将 minimumCacheTTL 保持在较低水平。否则,您可能需要手动更改 src 属性或删除缓存文件 <distDir>/cache/images

disableStaticImages

disableStaticImages 允许您禁用静态图像导入。

默认行为允许您导入静态文件,例如 import icon from './icon.png',然后将其传递给 src 属性。在某些情况下,如果它与其他预期导入行为不同的插件冲突,您可能希望禁用此功能。

您可以在 next.config.js 中禁用静态图像导入

next.config.js
module.exports = {
  images: {
    disableStaticImages: true,
  },
}

maximumRedirects

默认图像优化加载器在获取远程图像时将最多跟随 3 次 HTTP 重定向。

next.config.js
module.exports = {
  images: {
    maximumRedirects: 3,
  },
}

您可以配置获取远程图像时要跟随的重定向次数。将值设置为 0 将禁用跟随重定向。

next.config.js
module.exports = {
  images: {
    maximumRedirects: 0,
  },
}

dangerouslyAllowLocalIP

在极少数情况下,当在私有网络上自托管 Next.js 时,您可能希望允许优化来自同一网络上的本地 IP 地址的图像。对于大多数用户来说不建议这样做,因为它可能允许恶意用户访问您的内部网络上的内容。

默认情况下,值为 false。

next.config.js
module.exports = {
  images: {
    dangerouslyAllowLocalIP: false,
  },
}

如果您需要优化托管在本地网络其他地方的远程图像,可以将此值设置为 true。

next.config.js
module.exports = {
  images: {
    dangerouslyAllowLocalIP: true,
  },
}

dangerouslyAllowSVG

dangerouslyAllowSVG 允许您提供 SVG 图像。

next.config.js
module.exports = {
  images: {
    dangerouslyAllowSVG: true,
  },
}

默认情况下,Next.js 不优化 SVG 图像,原因有以下几点

  • SVG 是一种矢量格式,这意味着它可以无损地调整大小。
  • SVG 具有许多与 HTML/CSS 相同的功能,如果没有适当的内容安全策略 (CSP) 头部,可能会导致漏洞。

src 属性已知为 SVG 时,我们建议使用 unoptimized 属性。当 src".svg" 结尾时,这会自动发生。

<Image src="/my-image.svg" unoptimized />

此外,强烈建议同时设置 contentDispositionType 强制浏览器下载图像,并设置 contentSecurityPolicy 以防止嵌入图像中的脚本执行。

next.config.js
module.exports = {
  images: {
    dangerouslyAllowSVG: true,
    contentDispositionType: 'attachment',
    contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },
}

contentDispositionType

contentDispositionType 允许您配置 Content-Disposition 头部。

next.config.js
module.exports = {
  images: {
    contentDispositionType: 'inline',
  },
}

contentSecurityPolicy

contentSecurityPolicy 允许您为图像配置 Content-Security-Policy 头部。这在使用 dangerouslyAllowSVG 时尤为重要,以防止嵌入图像中的脚本执行。

next.config.js
module.exports = {
  images: {
    contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },
}

默认情况下,加载器Content-Disposition 标头设置为 attachment 以增加保护,因为 API 可以提供任意远程图像。

默认值为 attachment,它强制浏览器在直接访问时下载图像,而不是呈现图像。这在 dangerouslyAllowSVG 为 true 时尤为重要。

您可以选择配置 inline,以允许浏览器在直接访问时呈现图像,而无需下载。

已弃用的配置选项

domains

警告:自 Next.js 14 起已弃用,转而使用严格的 remotePatterns,以保护您的应用程序免受恶意用户攻击。

remotePatterns 类似,domains 配置可用于提供外部图像的允许主机名列表。但是,domains 配置不支持通配符模式匹配,并且不能限制协议、端口或路径名。

由于大多数远程图像服务器在多个租户之间共享,因此使用 remotePatterns 更安全,以确保仅优化预期的图像。

以下是 next.config.js 文件中 domains 属性的示例

next.config.js
module.exports = {
  images: {
    domains: ['assets.acme.com'],
  },
}

函数

getImageProps

getImageProps 函数可用于获取将传递给底层 <img> 元素的属性,并将其传递给另一个组件、样式、画布等。

import { getImageProps } from 'next/image'
 
const { props } = getImageProps({
  src: 'https://example.com/image.jpg',
  alt: 'A scenic mountain view',
  width: 1200,
  height: 800,
})
 
function ImageWithCaption() {
  return (
    <figure>
      <img {...props} />
      <figcaption>A scenic mountain view</figcaption>
    </figure>
  )
}

这也可以避免调用 React useState(),从而带来更好的性能,但它不能与 placeholder 属性一起使用,因为占位符永远不会被移除。

已知浏览器错误

next/image 组件使用浏览器原生的延迟加载,在 Safari 15.4 之前的旧浏览器中可能会回退到预加载。当使用模糊占位符时,Safari 12 之前的旧浏览器将回退到空占位符。当使用 width/heightauto 的样式时,在 Safari 15 之前不支持保留纵横比的旧浏览器上可能导致布局偏移。更多详情,请参见此 MDN 视频

示例

图像样式

为图像组件设置样式类似于为普通 <img> 元素设置样式,但有一些准则需要牢记

使用 classNamestyle,而不是 styled-jsx。在大多数情况下,我们建议使用 className 属性。它可以是导入的 CSS 模块全局样式表等。

import styles from './styles.module.css'
 
export default function MyImage() {
  return <Image className={styles.image} src="/my-image.png" alt="My Image" />
}

您还可以使用 style 属性分配内联样式。

export default function MyImage() {
  return (
    <Image style={{ borderRadius: '8px' }} src="/my-image.png" alt="My Image" />
  )
}

使用 fill 时,父元素必须具有 position: relativedisplay: block。这对于在该布局模式下正确渲染图像元素是必需的。

<div style={{ position: 'relative' }}>
  <Image fill src="/my-image.png" alt="My Image" />
</div>

您不能使用 styled-jsx,因为它作用域于当前组件(除非您将样式标记为 global)。

静态导出响应式图像

当您导入静态图像时,Next.js 会根据文件自动设置其宽度和高度。您可以通过设置样式使图像具有响应性

Responsive image filling the width and height of its parent container
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
 
export default function Responsive() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <Image
        alt="Mountains"
        // Importing an image will
        // automatically set the width and height
        src={mountains}
        sizes="100vw"
        // Make the image display full width
        // and preserve its aspect ratio
        style={{
          width: '100%',
          height: 'auto',
        }}
      />
    </div>
  )
}

远程 URL 响应式图像

如果源图像是动态的或远程 URL,您必须提供 width 和 height 属性,以便 Next.js 可以计算纵横比

components/page.js
import Image from 'next/image'
 
export default function Page({ photoUrl }) {
  return (
    <Image
      src={photoUrl}
      alt="Picture of the author"
      sizes="100vw"
      style={{
        width: '100%',
        height: 'auto',
      }}
      width={500}
      height={300}
    />
  )
}

尝试一下

fill 的响应式图像

如果您不知道图像的纵横比,您可以添加 fill 属性并将 objectFit 属性设置为 cover。这将使图像填充其父容器的整个宽度。

Grid of images filling parent container width
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
 
export default function Fill() {
  return (
    <div
      style={{
        display: 'grid',
        gridGap: '8px',
        gridTemplateColumns: 'repeat(auto-fit, minmax(400px, auto))',
      }}
    >
      <div style={{ position: 'relative', width: '400px' }}>
        <Image
          alt="Mountains"
          src={mountains}
          fill
          sizes="(min-width: 808px) 50vw, 100vw"
          style={{
            objectFit: 'cover', // cover, contain, none
          }}
        />
      </div>
      {/* And more images in the grid... */}
    </div>
  )
}

背景图像

使用 fill 属性使图像覆盖整个屏幕区域

Background image taking full width and height of page
import Image from 'next/image'
import mountains from '../public/mountains.jpg'
 
export default function Background() {
  return (
    <Image
      alt="Mountains"
      src={mountains}
      placeholder="blur"
      quality={100}
      fill
      sizes="100vw"
      style={{
        objectFit: 'cover',
      }}
    />
  )
}

有关与各种样式一起使用的图像组件的示例,请参阅图像组件演示

远程图像

要使用远程图像,src 属性应为 URL 字符串。

app/page.js
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="https://s3.amazonaws.com/my-bucket/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

由于 Next.js 在构建过程中无法访问远程文件,您需要手动提供widthheight 和可选的blurDataURL 属性。

widthheight 属性用于推断图像的正确纵横比,并避免图像加载引起的布局偏移。widthheight 决定图像文件的渲染尺寸。

为了安全地允许优化图像,请在 next.config.js 中定义支持的 URL 模式列表。尽可能具体,以防止恶意使用。例如,以下配置将只允许来自特定 AWS S3 存储桶的图像

next.config.js
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
        search: '',
      },
    ],
  },
}

主题检测

如果您想为亮色和暗色模式显示不同的图像,您可以创建一个新组件,该组件包装两个 <Image> 组件,并根据 CSS 媒体查询显示正确的图像。

components/theme-image.module.css
.imgDark {
  display: none;
}
 
@media (prefers-color-scheme: dark) {
  .imgLight {
    display: none;
  }
  .imgDark {
    display: unset;
  }
}
components/theme-image.tsx
import styles from './theme-image.module.css'
import Image, { ImageProps } from 'next/image'
 
type Props = Omit<ImageProps, 'src' | 'preload' | '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" 的默认行为可确保仅加载正确的图像。您不能使用 preloadloading="eager",因为那会导致加载两个图像。相反,您可以使用 fetchPriority="high"

尝试一下

艺术指导

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

app/page.js
import { getImageProps } from 'next/image'
 
export default function Home() {
  const common = { alt: 'Art Direction Example', sizes: '100vw' }
  const {
    props: { srcSet: desktop },
  } = getImageProps({
    ...common,
    width: 1440,
    height: 875,
    quality: 80,
    src: '/desktop.jpg',
  })
  const {
    props: { srcSet: mobile, ...rest },
  } = getImageProps({
    ...common,
    width: 750,
    height: 1334,
    quality: 70,
    src: '/mobile.jpg',
  })
 
  return (
    <picture>
      <source media="(min-width: 1000px)" srcSet={desktop} />
      <source media="(min-width: 500px)" srcSet={mobile} />
      <img {...rest} style={{ width: '100%', height: 'auto' }} />
    </picture>
  )
}

背景 CSS

你甚至可以将srcSet字符串转换为image-set() CSS 函数,以优化背景图像。

app/page.js
import { getImageProps } from 'next/image'
 
function getBackgroundImage(srcSet = '') {
  const imageSet = srcSet
    .split(', ')
    .map((str) => {
      const [url, dpi] = str.split(' ')
      return `url("${url}") ${dpi}`
    })
    .join(', ')
  return `image-set(${imageSet})`
}
 
export default function Home() {
  const {
    props: { srcSet },
  } = getImageProps({ alt: '', width: 128, height: 128, src: '/img.png' })
  const backgroundImage = getBackgroundImage(srcSet)
  const style = { height: '100vh', width: '100vw', backgroundImage }
 
  return (
    <main style={style}>
      <h1>Hello World</h1>
    </main>
  )
}

版本历史

版本更改
v16.0.0qualities默认配置更改为[75],添加了preload属性,priority属性已弃用,添加了dangerouslyAllowLocalIP配置,添加了maximumRedirects配置。
v15.3.0remotePatterns添加了对URL对象数组的支持。
v15.0.0contentDispositionType配置默认值更改为attachment
v14.2.23添加了qualities配置。
v14.2.15添加了decoding属性和localPatterns配置。
v14.2.14添加了remotePatterns.search属性。
v14.2.0添加了overrideSrc属性。
v14.1.0getImageProps()稳定。
v14.0.0onLoadingComplete属性和domains配置已弃用。
v13.4.14placeholder属性支持data:/image...
v13.2.0添加了contentDispositionType配置。
v13.0.6添加了ref属性。
v13.0.0next/image导入重命名为next/legacy/imagenext/future/image导入重命名为next/image。提供了codemod,以安全自动地重命名你的导入。移除了<span>包装器。移除了layoutobjectFitobjectPositionlazyBoundarylazyRoot属性。alt是必需的。onLoadingComplete接收对img元素的引用。移除了内置加载器配置。
v12.3.0remotePatternsunoptimized配置稳定。
v12.2.0添加了实验性remotePatterns和实验性unoptimized配置。移除了layout="raw"
v12.1.1添加了style属性。添加了对layout="raw"的实验性支持。
v12.1.0添加了dangerouslyAllowSVGcontentSecurityPolicy配置。
v12.0.9添加了lazyRoot属性。
v12.0.0添加了formats配置。
添加了AVIF支持。
包装器<div>更改为<span>
v11.1.0添加了onLoadingCompletelazyBoundary属性。
v11.0.0src属性支持静态导入。
添加了placeholder属性。
添加了blurDataURL属性。
v10.0.5添加了loader属性。
v10.0.1添加了layout属性。
v10.0.0引入了next/image