跳到主要内容

Image Component

Next.js 的 Image 组件扩展了 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 文档,因为组件名称有变更。

参考

Props

可用的 props 如下:

Prop示例类型状态
srcsrc="/profile.png"String必填
altalt="Picture of the author"String必填
widthwidth={500}Integer (px)-
heightheight={500}Integer (px)-
fillfill={true}Boolean-
loaderloader={imageLoader}Function-
sizessizes="(max-width: 768px) 100vw, 33vw"String-
qualityquality={80}Integer (1-100)-
prioritypriority={true}Boolean-
placeholderplaceholder="blur"String-
stylestyle={{objectFit: "contain"}}Object-
onLoadingCompleteonLoadingComplete={img => done())}Function已弃用
onLoadonLoad={event => done())}Function-
onErroronError(event => fail()}Function-
loadingloading="lazy"String-
blurDataURLblurDataURL="data:image/jpeg..."String-
overrideSrcoverrideSrc="/seo.png"String-

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

alt

alt 属性用于为屏幕阅读器和搜索引擎描述图片。当图片被禁用或加载出错时,也会显示为回退文本。

应包含可以替代图片且不改变页面含义的文本。不应重复图片上下的说明文字。

如果图片是纯装饰性不面向用户alt 应设为空字符串(alt="")。

了解更多 图片可访问性指南

widthheight

widthheight 属性表示图片的固有尺寸(像素)。用于让浏览器预留正确的宽高比,避免加载时布局偏移。它不决定图片的实际渲染尺寸,实际渲染由 CSS 控制。

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

必须同时设置 widthheight,除非:

  • 图片是静态导入的;
  • 图片使用了 fill 属性

如果未知宽高,推荐使用 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}
/>
)
}

提示: 使用 onLoad 等接受函数作为参数的 props 需要使用 Client Components 序列化提供的函数。

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 实例配置加载器,而无需传递 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 等),优化响应式布局。

了解更多 srcsetsizesweb.devmdn 上的内容。

quality

一个介于 1100 之间的整数,用于设置优化后图片的质量。值越高,文件体积越大,视觉保真度越高。值越低,文件体积越小,但可能影响清晰度。

// 默认质量为 75
<Image quality={75} />

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

提示: 如果原始图片质量已经较低,设置较高的质量值会增加文件体积,但不会改善外观。

style

允许将 CSS 样式传递给底层的 <img> 元素。

const imageStyle = {
borderRadius: '50%',
border: '1px solid #fff',
width: '100px',
height: 'auto',
}

export default function ProfileImage() {
return <Image src="..." style={imageStyle} />
}

提示: 如果你使用 style 属性设置自定义宽度,请确保同时设置 height: 'auto' 以保持图片的宽高比。

priority

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

// 默认优先级为 false
<Image priority={false} />
  • true预加载图片。禁用懒加载。
  • false:懒加载图片。

何时使用:

何时不使用:

  • 当使用 loading 属性时(会触发警告)。

loading

控制图片的加载时机。

// 默认懒加载
<Image loading="lazy" />
  • lazy:延迟加载图片,直到它到达视口计算距离。
  • eager:立即加载图片,无论其在页面中的位置如何。

仅在需要确保图片立即加载时使用 eager

了解更多 loading 属性

placeholder

指定一个占位符,在图片加载时使用,以提高感知加载性能。

// 默认空
<Image placeholder="empty" />
  • empty:图片加载时无占位符。
  • blur:使用图片的模糊版本作为占位符。必须与 blurDataURL 属性一起使用。
  • data:image/...:使用 Data URL 作为占位符。

示例:

了解更多 placeholder 属性

blurDataURL

一个 Data URL,用于在图片成功加载之前作为占位符。可以自动设置或与 placeholder="blur" 属性一起使用。

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

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

自动

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

手动设置

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

一个较大的 blurDataURL 可能会影响性能。保持小巧简单。

示例:

onLoad

一个回调函数,在图片完全加载且 placeholder 被移除时调用。

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

回调函数将接收一个参数,即事件,其 target 属性引用底层的 <img> 元素。

提示: 使用 onLoad 等接受函数作为参数的 props 需要使用 Client Components 序列化提供的函数。

onError

一个回调函数,在图片加载失败时调用。

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

提示: 使用 onError 等接受函数作为参数的 props 需要使用 Client Components 序列化提供的函数。

unoptimized

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

import Image from 'next/image'

const UnoptimizedImage = (props) => {
// 默认值为 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 prop 时,next/image 会自动生成 <img>srcsetsrc 属性。

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 prop 覆盖它。

例如,当你从 <img> 升级到 <Image> 时,你可能希望保持相同的 src 属性以进行 SEO,例如图片排名或避免重新抓取。

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

一个提示,告知浏览器是否应在展示其他内容更新或不展示之前等待图片解码。

// 默认异步
<Image decoding="async" />
  • async:异步解码图片,并允许在完成前渲染其他内容。
  • sync:同步解码图片,与其他内容原子性展示。
  • auto:无偏好。浏览器选择最佳方法。

了解更多 decoding 属性

其他 Props

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

已弃用的 props

onLoadingComplete

警告: 已弃用,请使用 onLoad 替代。

一个回调函数,在图片完全加载且 placeholder 被移除时调用。

回调函数将接收一个参数,即底层的 <img> 元素的引用。

'use client'

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

提示: 使用 onLoadingComplete 等接受函数作为参数的 props 需要使用 Client Components 序列化提供的函数。

配置选项

你可以在 next.config.js 中配置 Image 组件。以下选项可用:

localPatterns

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

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

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

remotePatterns

next.config.js 文件中使用 remotePatterns 来允许从特定外部路径和阻止所有其他路径。这确保了只有你的账户提供的图片才能被提供。

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

如果你使用的是 15.3.0 之前的版本,你可以使用对象配置 remotePatterns

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

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

通配符模式

通配符模式可以用于 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 Bad Request。

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

示例:

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

deviceSizes

deviceSizes 允许你指定一个设备宽度断点列表。这些宽度在 next/image 组件使用 sizes 属性时用于确保为用户设备提供正确的图片。

如果没有提供配置,则使用以下默认值:

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

imageSizes

imageSizes 允许你指定一个图片宽度列表。这些宽度与 device sizes 数组连接,形成用于生成图片 srcset 的完整尺寸数组。

如果没有提供配置,则使用以下默认值:

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

imageSizes 仅在图片提供 sizes 属性 时使用,该属性表明图片小于屏幕宽度。因此,imageSizes 中的尺寸应小于 deviceSizes 中的最小尺寸。

qualities

qualities 允许你指定一个图片质量值列表。

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

上述示例中,只允许三个质量:25、50 和 75。如果 quality 属性不匹配此数组中的任何值,图片将失败并响应 400 Bad Request。

formats

formats 允许你指定一个图片格式列表。

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

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

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

你可以启用 AVIF 支持,这会在浏览器 不支持 AVIF 时回退到源图片的格式:

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

提示:

  • 我们仍然建议大多数情况下使用 WebP。
  • AVIF 通常需要 50% 更长的编码时间,但压缩率比 WebP 小 20%。这意味着第一次请求图片时通常会较慢,但缓存后的后续请求会更快。
  • 如果你在 Next.js 前端自托管并使用代理/CDN,你必须配置代理以转发 Accept 头。

minimumCacheTTL

minimumCacheTTL 允许你配置缓存优化图片的 Time to Live (TTL) 秒数。在许多情况下,使用 静态图片导入 是更好的选择,它会自动哈希文件内容并缓存图片,并带有 Cache-Controlimmutable

如果没有提供配置,则使用以下默认值:

next.config.js
module.exports = {
images: {
minimumCacheTTL: 60, // 1 分钟
},
}

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

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

优化图片的过期(或 Max Age)由 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,
},
}

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

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

默认值为 attachment,这会强制浏览器在直接访问时下载图片。这对于 dangerouslyAllowSVG 属性 为 true 特别重要。

你可以选择性地配置 inline,以允许浏览器在直接访问时渲染图片,而不下载它。

已弃用的配置选项

domains

警告: 自 Next.js 14 起,已弃用,为保护应用免受恶意用户攻击,请使用严格的 remotePatterns 替代。仅当你拥有从该域名提供的所有内容时才使用 domains

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

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

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

函数

getImageProps

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

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 属性一起使用,因为占位符永远不会被移除。

已知浏览器 bug

next/image 组件使用浏览器原生的 懒加载,在 Safari 15.4 之前可能会回退到急加载。使用模糊占位符时,Safari 12 之前的浏览器会回退到空占位符。当使用带有 width/heightauto 的样式时,在 Safari 15 之前的浏览器中可能会导致 布局偏移。有关更多详细信息,请参见 此 MDN 视频

示例

图片样式

图片组件的样式与普通 <img> 元素的样式类似,但有一些注意事项:

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

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 containerResponsive 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"
// 导入图片会
// 自动设置宽度和高度
src={mountains}
sizes="100vw"
// 使图片显示全宽
// 并保持其宽高比
style={{
width: '100%',
height: 'auto',
}}
/>
</div>
)
}

响应式图片与远程 URL

如果源图片是动态或远程 URL,你必须提供 widthheight 属性,以便 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 属性 并设置 objectFitcover。这将使图片填满其父容器宽度。

Grid of images filling parent container widthGrid 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>
{/* 更多图片在网格中... */}
</div>
)
}

背景图片

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

Background image taking full width and height of pageBackground 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' | '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"

试试看:

艺术指导

如果你想根据移动端和桌面端显示不同的图片,有时称为 艺术指导,你可以为 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>
)
}

版本历史

版本变更
v15.3.0remotePatterns 添加了对 URL 对象数组的支持。
v15.0.0contentDispositionType 配置默认值更改为 attachment
v14.2.23qualities 配置添加。
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.0contentDispositionType 配置添加。
v13.0.6ref 属性添加。
v13.0.0next/image 导入已重命名为 next/legacy/imagenext/future/image 导入已重命名为 next/imagecodemod 可用 以安全且自动重命名你的导入。<span> 包装已移除。layoutobjectFitobjectPositionlazyBoundarylazyRoot 属性已移除。alt 为必填。onLoadingComplete 接收 img 元素的引用。内置加载器配置已移除。
v12.3.0remotePatternsunoptimized 配置已稳定。
v12.2.0实验性 remotePatterns 和实验性 unoptimized 配置添加。layout="raw" 已移除。
v12.1.1style 属性添加。实验性 layout="raw" 支持添加。
v12.1.0dangerouslyAllowSVGcontentSecurityPolicy 配置添加。
v12.0.9lazyRoot 属性添加。
v12.0.0formats 配置添加。
AVIF 支持添加。
包装 <div> 更改为 <span>
v11.1.0onLoadingCompletelazyBoundary 属性添加。
v11.0.0src 属性支持静态导入。
placeholder 属性添加。
blurDataURL 属性添加。
v10.0.5loader 属性添加。
v10.0.1layout 属性添加。
v10.0.0next/image 引入。