跳到内容
API 参考组件图像组件

图像组件

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

参考

属性

以下 props 可用

属性示例类型状态
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 字符串

'use client'
 
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}
    />
  )
}

温馨提示:使用接受函数的 props(如 onLoad)需要使用 客户端组件 来序列化提供的函数。

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

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

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

自动

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

手动设置

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

大的 blurDataURL 可能会损害性能。保持它小而简单。

示例

onLoad

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

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

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

温馨提示:使用接受函数的 props(如 onLoad)需要使用 客户端组件 来序列化提供的函数。

onError

图像加载失败时调用的回调函数。

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

温馨提示:使用接受函数的 props(例如 onError)需要使用 客户端组件 来序列化提供的函数。

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

当向 <Image> 组件提供 src 属性时,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 元素,但以下情况除外

已废弃的 props

onLoadingComplete

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

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

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

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

温馨提示:使用接受函数的 props(例如 onLoadingComplete)需要使用 客户端组件 来序列化提供的函数。

配置选项

您可以在 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
'use client'
 
export default function myImageLoader({ src, width, quality }) {
  return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}

示例

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

path

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

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

deviceSizes

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

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

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 prop 的图像,这表示图像小于屏幕的完整宽度。因此,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

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

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 prop 分配内联样式。

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 props,以便 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