图片
Examples
此 API 参考将帮助你了解如何使用可用于图片组件的 props 和 配置选项。功能及使用方法请参见 图片组件 页。
¥This API reference will help you understand how to use props and configuration options available for the Image Component. For features and usage, please see the Image Component page.
import Image from 'next/image'
export default function Page() {
return (
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
)
}
属性
¥Props
以下是图片组件可用的 props 的摘要:
¥Here's a summary of the props available for the Image Component:
属性 | 示例 | 类型 | 地位 |
---|---|---|---|
src | src="/profile.png" | 字符串 | 必需的 |
width | width={500} | 整数(像素) | 必需的 |
height | height={500} | 整数(像素) | 必需的 |
alt | alt="Picture of the author" | 字符串 | 必需的 |
loader | loader={imageLoader} | 函数 | * |
fill | fill={true} | 布尔值 | * |
sizes | sizes="(max-width: 768px) 100vw, 33vw" | 字符串 | * |
quality | quality={80} | 整数(1-100) | * |
priority | priority={true} | 布尔值 | * |
placeholder | placeholder="blur" | 字符串 | * |
style | style={{objectFit: "contain"}} | 目的 | * |
onLoadingComplete | onLoadingComplete={img => done())} | 函数 | 已弃用 |
onLoad | onLoad={event => done())} | 函数 | * |
onError | onError(event => fail()} | 函数 | * |
loading | loading="lazy" | 字符串 | * |
blurDataURL | blurDataURL="data:image/jpeg..." | 字符串 | * |
overrideSrc | overrideSrc="/seo.png" | 字符串 | * |
必需属性
¥Required Props
图片组件需要以下属性:src
、alt
、width
和 height
(或 fill
)。
¥The Image Component requires the following properties: src
, alt
, width
and height
(or fill
).
import Image from 'next/image'
export default function Page() {
return (
<div>
<Image
src="/profile.png"
width={500}
height={500}
alt="Picture of the author"
/>
</div>
)
}
src
必须是以下之一:
¥Must be one of the following:
-
静态导入 图片文件
¥A statically imported image file
-
路径字符串。这可以是绝对外部 URL,也可以是内部路径,具体取决于 loader 属性。
¥A path string. This can be either an absolute external URL, or an internal path depending on the loader prop.
使用外部 URL 时,必须将其添加到 next.config.js
中的 remotePatterns 中。
¥When using an external URL, you must add it to remotePatterns in next.config.js
.
width
width
属性表示以像素为单位的内部图片宽度。
¥The width
property represents the intrisic image width in pixels.
¥Required, except for statically imported images or images with the fill
property.
height
height
属性表示以像素为单位的内部图片高度。
¥The height
property represents the intrisic image height in pixels.
¥Required, except for statically imported images or images with the fill
property.
很高兴知道:
¥Good to know:
结合起来,
width
和height
属性都用于确定图片的纵横比,浏览器使用该纵横比在图片加载之前为其保留空间。¥Combined, both
width
andheight
properties are used to determine the aspect ratio of the image which used by browsers to reserve space for the image before it loads.固有大小并不总是意味着浏览器中的渲染大小,这将由父容器决定。例如,如果父容器小于固有大小,则图片将缩小以适合容器。
¥The intrinsic size does not always mean the rendered size in the browser, which will be determined by the parent container. For example, if the parent container is smaller than the intrinsic size, the image will be scaled down to fit the container.
当宽度和高度未知时,你可以使用
fill
属性。¥You can use the
fill
property when the width and height are unknown.
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=""
).
可选属性
¥Optional Props
<Image />
组件接受除所需属性之外的许多附加属性。本节介绍 Image 组件最常用的属性。在 高级属性 部分中查找更多很少使用的属性的详细信息。
¥The <Image />
component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the Advanced Props section.
loader
用于解析图片 URL 的自定义函数。
¥A custom function used to resolve image URLs.
loader
是一个返回图片 URL 字符串的函数,给定以下参数:
¥A loader
is a function returning a URL string for the image, given the following parameters:
这是使用自定义加载程序的示例:
¥Here is an example of using a custom loader:
'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}
/>
)
}
很高兴知道:使用像
loader
这样接受函数的 props,需要使用 客户端组件 来序列化提供的函数。¥Good to know: Using props like
loader
, which accept a function, requires using Client Components to serialize the provided function.
或者,你可以使用 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.
fill
fill={true} // {true} | {false}
导致图片填充父元素的布尔值,当 width
和 height
未知时很有用。
¥A boolean that causes the image to fill the parent element, which is useful when the width
and height
are unknown.
父元素必须指定 position: "relative"
、position: "fixed"
或 position: "absolute"
样式。
¥The parent element must assign position: "relative"
, position: "fixed"
, or position: "absolute"
style.
默认情况下,img 元素将自动分配 position: "absolute"
样式。
¥By default, the img element will automatically be assigned the position: "absolute"
style.
如果没有对图片应用样式,图片将拉伸以适合容器。你可能更愿意为带有信箱的图片设置 object-fit: "contain"
以适合容器并保留宽高比。
¥If no styles are applied to the image, the image will stretch to fit the container. You may prefer to set object-fit: "contain"
for an image which is letterboxed to fit the container and preserve aspect ratio.
或者,object-fit: "cover"
将使图片填充整个容器并被裁剪以保留纵横比。
¥Alternatively, object-fit: "cover"
will cause the image to fill the entire container and be cropped to preserve aspect ratio.
有关更多信息,另请参阅:
¥For more information, see also:
sizes
类似于媒体查询的字符串,提供有关图片在不同断点处的宽度的信息。sizes
的值将极大地影响使用 fill
或 设计为具有响应式尺寸 的图片的性能。
¥A string, similar to a media query, that provides information about how wide the image will be at different breakpoints. The value of sizes
will greatly affect performance for images using fill
or which are styled to have a responsive size.
sizes
属性有两个与图片性能相关的重要目的:
¥The sizes
property serves two important purposes related to image performance:
-
首先,浏览器使用
sizes
的值来确定要下载的图片大小,来自next/image
的自动生成的srcset
。当浏览器选择时,它还不知道页面上图片的大小,因此它选择与视口大小相同或更大的图片。sizes
属性允许你告诉浏览器图片实际上小于全屏。如果你未使用fill
属性在图片中指定sizes
值,则使用默认值100vw
(全屏宽度)。¥First, the value of
sizes
is used by the browser to determine which size of the image to download, fromnext/image
's automatically generatedsrcset
. When the browser chooses, it does not yet know the size of the image on the page, so it selects an image that is the same size or larger than the viewport. Thesizes
property allows you to tell the browser that the image will actually be smaller than full screen. If you don't specify asizes
value in an image with thefill
property, a default value of100vw
(full screen width) is used. -
其次,
sizes
属性更改自动生成的srcset
值的行为。如果不存在sizes
值,则会生成一个小的srcset
,适用于固定尺寸图片(1x/2x/等)。如果定义了sizes
,则会生成一个大的srcset
,适合响应式图片(640w/750w/等)。如果sizes
属性包含诸如50vw
之类的尺寸(代表视口宽度的百分比),则srcset
会被修剪以不包含任何太小而不必要的值。¥Second, the
sizes
property changes the behavior of the automatically generatedsrcset
value. If nosizes
value is present, a smallsrcset
is generated, suitable for a fixed-size image (1x/2x/etc). Ifsizes
is defined, a largesrcset
is generated, suitable for a responsive image (640w/750w/etc). If thesizes
property includes sizes such as50vw
, which represent a percentage of the viewport width, then thesrcset
is trimmed to not include any values which are too small to ever be necessary.
例如,如果你知道你的样式将导致图片在移动设备上为全宽、在平板电脑上为 2 列布局、在桌面显示器上为 3 列布局,则应包含尺寸属性,如下所示 :
¥For example, if you know your styling will cause an image to be full-width on mobile devices, in a 2-column layout on tablets, and a 3-column layout on desktop displays, you should include a sizes property such as the following:
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
可能会对性能指标产生巨大影响。如果没有 33vw
尺寸,从服务器选择的图片宽度将是所需宽度的 3 倍。由于文件大小与宽度的平方成正比,因此如果没有 sizes
,用户将下载比所需大小大 9 倍的图片。
¥This example sizes
could have a dramatic effect on performance metrics. Without the 33vw
sizes, the image selected from the server would be 3 times as wide as it needs to be. Because file size is proportional to the square of the width, without sizes
the user would download an image that's 9 times larger than necessary.
了解有关 srcset
和 sizes
的更多信息:
¥Learn more about srcset
and sizes
:
quality
quality={75} // {number 1-100}
优化图片的质量,1
和 100
之间的整数,其中 100
是最佳质量,因此文件大小最大。默认为 75
。
¥The quality of the optimized image, an integer between 1
and 100
, where 100
is the best quality and therefore largest file size. Defaults to 75
.
priority
priority={false} // {false} | {true}
如果为 true,则图片将被视为高优先级和 preload。使用 priority
的图片会自动禁用延迟加载。
¥When true, the image will be considered high priority and
preload. Lazy loading is automatically disabled for images using priority
.
你应该对检测为 最大内容涂料 (LCP) 元素的任何图片使用 priority
属性。具有多个优先级图片可能是合适的,因为不同的图片可能是不同视口尺寸的 LCP 元素。
¥You should use the priority
property on any image detected as the Largest Contentful Paint (LCP) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes.
仅当图片在首屏上方可见时才应使用。默认为 false
。
¥Should only be used when the image is visible above the fold. Defaults to false
.
placeholder
placeholder = 'empty' // "empty" | "blur" | "data:image/..."
加载图片时使用的占位符。可能的值为 blur
、empty
或 data:image/...
。默认为 empty
。
¥A placeholder to use while the image is loading. Possible values are blur
, empty
, or data:image/...
. Defaults to empty
.
当 blur
时,blurDataURL
属性将用作占位符。如果 src
是 静态导入 中的对象,并且导入的图片是 .jpg
、.png
、.webp
或 .avif
,则 blurDataURL
将自动填充,除非检测到图片是动画的。
¥When blur
, the blurDataURL
property will be used as the placeholder. If src
is an object from a static import and the imported image is .jpg
, .png
, .webp
, or .avif
, then blurDataURL
will be automatically populated, except when the image is detected to be animated.
对于动态图片,你必须提供 blurDataURL
属性。占位符 等解决方案可以帮助生成 base64
。
¥For dynamic images, you must provide the blurDataURL
property. Solutions such as Plaiceholder can help with base64
generation.
当 data:image/...
时,数据网址 将在图片加载时用作占位符。
¥When data:image/...
, the Data URL will be used as the placeholder while the image is loading.
当 empty
时,图片加载时不会有占位符,只有空白空间。
¥When empty
, there will be no placeholder while the image is loading, only empty space.
试试看:
¥Try it out:
高级属性
¥Advanced Props
在某些情况下,你可能需要更高级的用法。<Image />
组件可选择接受以下高级属性。
¥In some cases, you may need more advanced usage. The <Image />
component optionally accepts the following advanced properties.
style
允许将 CSS 样式传递给底层图片元素。
¥Allows passing CSS styles to the underlying image element.
const imageStyle = {
borderRadius: '50%',
border: '1px solid #fff',
}
export default function ProfileImage() {
return <Image src="..." style={imageStyle} />
}
请记住,所需的宽度和高度属性可以与你的样式交互。如果你使用样式来修改图片的宽度,你还应该将其高度样式设置为 auto
以保留其固有的纵横比,否则你的图片将会扭曲。
¥Remember that the required width and height props can interact with your styling. If you use styling to modify an image's width, you should also style its height to auto
to preserve its intrinsic aspect ratio, or your image will be distorted.
onLoadingComplete
'use client'
<Image onLoadingComplete={(img) => console.log(img.naturalWidth)} />
警告:自 Next.js 14 起已弃用,代之以
onLoad
。¥Warning: Deprecated since Next.js 14 in favor of
onLoad
.
图片完全加载且 placeholder 已删除后调用的回调函数。
¥A callback function that is invoked once the image is completely loaded and the placeholder has been removed.
回调函数将使用一个参数调用,即对底层 <img>
元素的引用。
¥The callback function will be called with one argument, a reference to the underlying <img>
element.
很高兴知道:使用像
onLoadingComplete
这样接受函数的 props,需要使用 客户端组件 来序列化提供的函数。¥Good to know: Using props like
onLoadingComplete
, which accept a function, requires using Client Components to serialize the provided function.
onLoad
<Image onLoad={(e) => console.log(e.target.naturalWidth)} />
图片完全加载且 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.
很高兴知道:使用像
onLoad
这样接受函数的 props,需要使用 客户端组件 来序列化提供的函数。¥Good to know: Using props like
onLoad
, which accept a function, requires using Client Components to serialize the provided function.
onError
<Image onError={(e) => console.error(e.target.id)} />
图片加载失败时调用的回调函数。
¥A callback function that is invoked if the image fails to load.
很高兴知道:使用像
onError
这样接受函数的 props,需要使用 客户端组件 来序列化提供的函数。¥Good to know: Using props like
onError
, which accept a function, requires using Client Components to serialize the provided function.
loading
推荐:此属性仅适用于高级用例。切换图片以使用
eager
加载通常会损害性能。我们建议改用priority
属性,它会预加载图片。¥Recommendation: This property is only meant for advanced use cases. Switching an image to load with
eager
will normally hurt performance. We recommend using thepriority
property instead, which will eagerly preload the image.
loading = 'lazy' // {lazy} | {eager}
图片的加载行为。默认为 lazy
。
¥The loading behavior of the image. Defaults to lazy
.
当 lazy
时,推迟加载图片,直到它达到距视口的计算距离。
¥When lazy
, defer loading the image until it reaches a calculated distance from
the viewport.
当 eager
时,立即加载图片。
¥When eager
, load the image immediately.
了解有关 loading
属性 的更多信息。
¥Learn more about the loading
attribute.
blurDataURL
在成功加载 src
图片之前,将 数据网址 用作占位符图片。仅与 placeholder="blur"
组合时生效。
¥A Data URL to
be used as a placeholder image before the src
image successfully loads. Only takes effect when combined
with placeholder="blur"
.
必须是 base64 编码的图片。它会被放大并模糊,因此建议使用非常小的图片(10px 或更小)。包含较大的图片作为占位符可能会损害你的应用性能。
¥Must be a base64-encoded image. It will be enlarged and blurred, so a very small image (10px or less) is recommended. Including larger images as placeholders may harm your application performance.
试试看:
¥Try it out:
你还可以 生成纯色数据 URL 来匹配图片。
¥You can also generate a solid color Data URL to match the image.
unoptimized
unoptimized = {false} // {false} | {true}
如果为 true,则源图片将按原样提供,而不是更改质量、大小或格式。默认为 false
。
¥When true, the source image will be served as-is instead of changing quality,
size, or format. Defaults to false
.
import Image from 'next/image'
const UnoptimizedImage = (props) => {
return <Image {...props} unoptimized />
}
从 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:
module.exports = {
images: {
unoptimized: true,
},
}
overrideSrc
当向 <Image>
组件提供 src
属性时,会为生成的 <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>
.
<Image src="/me.jpg" />
<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
属性覆盖它。
¥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.
<Image src="/me.jpg" overrideSrc="/override.jpg" />
<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"
/>
其他属性
¥Other Props
<Image />
组件上的其他属性将传递给底层 img
元素,但以下属性除外:
¥Other properties on the <Image />
component will be passed to the underlying
img
element with the exception of the following:
-
srcSet
。请改用 设备尺寸。¥
srcSet
. Use Device Sizes instead. -
decoding
。始终是"async"
。¥
decoding
. It is always"async"
.
配置选项
¥Configuration Options
除了 props 之外,你还可以在 next.config.js
中配置 Image 组件。可以使用以下选项:
¥In addition to props, you can configure the Image Component in next.config.js
. The following options are available:
remotePatterns
为了保护你的应用免受恶意用户的侵害,需要进行配置才能使用外部映像。这可确保 Next.js 图片优化 API 只能提供你账户中的外部图片。这些外部图片可以使用 next.config.js
文件中的 remotePatterns
属性进行配置,如下所示:
¥To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the remotePatterns
property in your next.config.js
file, as shown below:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
很高兴知道:上面的示例将确保
next/image
的src
属性必须以https://example.com/account123/
开头。任何其他协议、主机名、端口或不匹配的路径都将响应 400 Bad Request。¥Good to know: The example above will ensure the
src
property ofnext/image
must start withhttps://example.com/account123/
. Any other protocol, hostname, port, or unmatched path will respond with 400 Bad Request.
下面是 next.config.js
文件中 remotePatterns
属性的另一个示例:
¥Below is another example of the remotePatterns
property in the next.config.js
file:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
port: '',
},
],
},
}
很高兴知道:上面的示例将确保
next/image
的src
属性必须以https://img1.example.com
或https://me.avatar.example.com
或任意数量的子域开头。任何其他协议、端口或不匹配的主机名都将响应 400 Bad Request。¥Good to know: The example above will ensure the
src
property ofnext/image
must start withhttps://img1.example.com
orhttps://me.avatar.example.com
or any number of subdomains. Any other protocol, port, or unmatched hostname will respond with 400 Bad Request.
通配符模式可用于 pathname
和 hostname
,并具有以下语法:
¥Wildcard patterns can be used for both pathname
and hostname
and have the following syntax:
-
*
匹配单个路径段或子域¥
*
match a single path segment or subdomain -
**
匹配末尾任意数量的路径段或开头的子域¥
**
match any number of path segments at the end or subdomains at the beginning
**
语法在模式中间不起作用。
¥The **
syntax does not work in the middle of the pattern.
很高兴知道:当省略
protocol
、port
或pathname
时,则隐含通配符**
。不建议这样做,因为它可能会让恶意行为者优化你不希望的 URL。¥Good to know: When omitting
protocol
,port
orpathname
, then the wildcard**
is implied. This is not recommended because it may allow malicious actors to optimize urls you did not intend.
domains
警告:自 Next.js 14 起已弃用,取而代之的是严格的
remotePatterns
,以保护你的应用免受恶意用户的侵害。仅当你拥有该域提供的所有内容时才使用domains
。¥Warning: Deprecated since Next.js 14 in favor of strict
remotePatterns
in order to protect your application from malicious users. Only usedomains
if you own all the content served from the domain.
与 remotePatterns
类似,domains
配置可用于提供外部映像允许的主机名列表。
¥Similar to remotePatterns
, the domains
configuration can be used to provide a list of allowed hostnames for external images.
但是,domains
配置不支持通配符模式匹配,并且无法限制协议、端口或路径名。
¥However, the domains
configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname.
以下是 next.config.js
文件中 domains
属性的示例:
¥Below is an example of the domains
property in the next.config.js
file:
module.exports = {
images: {
domains: ['assets.acme.com'],
},
}
loaderFile
如果你想使用云提供商来优化图片,而不是使用 Next.js 内置图片优化 API,你可以在 next.config.js
中配置 loaderFile
,如下所示:
¥If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the loaderFile
in your next.config.js
like the following:
module.exports = {
images: {
loader: 'custom',
loaderFile: './my/image/loader.js',
},
}
这必须指向相对于 Next.js 应用根目录的文件。该文件必须导出返回字符串的默认函数,例如:
¥This must point to a file relative to the root of your Next.js application. The file must export a default function that returns a string, for example:
'use client'
export default function myImageLoader({ src, width, quality }) {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
或者,你可以使用 loader
属性 来配置 next/image
的每个实例。
¥Alternatively, you can use the loader
prop to configure each instance of next/image
.
示例:
¥Examples:
很高兴知道:自定义接受函数的图片加载器文件,需要使用 客户端组件 来序列化提供的函数。
¥Good to know: Customizing the image loader file, which accepts a function, requires using Client Components to serialize the provided function.
高级
¥Advanced
以下配置适用于高级用例,通常不是必需的。如果你选择配置以下属性,你将在未来的更新中覆盖对 Next.js 默认值的任何更改。
¥The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.
deviceSizes
如果你知道用户期望的设备宽度,则可以使用 next.config.js
中的 deviceSizes
属性指定设备宽度断点列表。当 next/image
组件使用 sizes
属性时,将使用这些宽度,以确保为用户设备提供正确的图片。
¥If you know the expected device widths of your users, you can specify a list of device width breakpoints using the deviceSizes
property in next.config.js
. These widths are used when the next/image
component uses sizes
prop to ensure the correct image is served for user's device.
如果未提供配置,则使用以下默认值。
¥If no configuration is provided, the default below is used.
module.exports = {
images: {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
}
imageSizes
你可以使用 next.config.js
文件中的 images.imageSizes
属性指定图片宽度列表。这些宽度与 设备尺寸 数组连接,形成用于生成图片 srcset 的完整尺寸数组。
¥You can specify a list of image widths using the images.imageSizes
property in your next.config.js
file. These widths are concatenated with the array of device sizes to form the full array of sizes used to generate image srcsets.
存在两个单独列表的原因是 imageSizes 仅用于提供 sizes
属性的图片,这表明图片小于屏幕的整个宽度。因此,imageSizes 中的尺寸都应小于 deviceSizes 中的最小尺寸。
¥The reason there are two separate lists is that imageSizes is only used for images which provide a sizes
prop, which indicates that the image is less than the full width of the screen. Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.
如果未提供配置,则使用以下默认值。
¥If no configuration is provided, the default below is used.
module.exports = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
formats
默认的 图片优化 API 会通过请求的 Accept
标头自动检测浏览器支持的图片格式。
¥The default Image Optimization API will automatically detect the browser's supported image formats via the request's Accept
header.
如果 Accept
头与多个配置格式匹配,则使用数组中的第一个匹配项。因此,数组顺序很重要。如果没有匹配(或源图片是 animated),图片优化 API 将回退到原始图片的格式。
¥If the Accept
head matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match (or the source image is animated), the Image Optimization API will fallback to the original image's format.
如果未提供配置,则使用以下默认值。
¥If no configuration is provided, the default below is used.
module.exports = {
images: {
formats: ['image/webp'],
},
}
你可以通过以下配置启用 AVIF 支持。
¥You can enable AVIF support with the following configuration.
module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
},
}
很高兴知道:
¥Good to know:
与 WebP 相比,AVIF 的编码时间通常要长 20%,但压缩率要小 20%。这意味着第一次请求图片时,通常会较慢,然后缓存的后续请求会更快。
¥AVIF generally takes 20% longer to encode but it compresses 20% smaller compared to WebP. This means that the first time an image is requested, it will typically be slower and then subsequent requests that are cached will be faster.
如果你在 Next.js 前面使用代理/CDN 进行自托管,则必须配置代理以转发
Accept
标头。¥If you self-host with a Proxy/CDN in front of Next.js, you must configure the Proxy to forward the
Accept
header.
缓存行为
¥Caching Behavior
下面介绍默认 loader 的缓存算法。对于所有其他加载程序,请参阅你的云提供商的文档。
¥The following describes the caching algorithm for the default loader. For all other loaders, please refer to your cloud provider's documentation.
图片根据请求动态优化并存储在 <distDir>/cache/images
目录中。优化后的图片文件将用于后续请求,直到到期。当发出与缓存但过期的文件匹配的请求时,过期的图片将立即失效。然后,图片在后台再次优化(也称为重新验证)并使用新的到期日期保存到缓存中。
¥Images are optimized dynamically upon request and stored in the <distDir>/cache/images
directory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the expired image is served stale immediately. Then the image is optimized again in the background (also called revalidation) and saved to the cache with the new expiration date.
通过读取 x-nextjs-cache
响应头的值可以确定图片的缓存状态。可能的值如下:
¥The cache status of an image can be determined by reading the value of the x-nextjs-cache
response header. The possible values are the following:
-
MISS
- 该路径不在缓存中(最多出现一次,在第一次访问时)¥
MISS
- the path is not in the cache (occurs at most once, on the first visit) -
STALE
- 该路径在缓存中,但超出了重新验证时间,因此它将在后台更新¥
STALE
- the path is in the cache but exceeded the revalidate time so it will be updated in the background -
HIT
- 该路径在缓存中并且未超过重新验证时间¥
HIT
- the path is in the cache and has not exceeded the revalidate time
过期(或更确切地说是最大期限)由 minimumCacheTTL
配置或上游映像 Cache-Control
标头定义,以较大者为准。具体来说,使用 Cache-Control
报头的 max-age
值。如果同时找到 s-maxage
和 max-age
,则首选 s-maxage
。max-age
还会传递到任何下游客户端,包括 CDN 和浏览器。
¥The expiration (or rather Max Age) is defined by either the minimumCacheTTL
configuration or the upstream image Cache-Control
header, whichever is larger. Specifically, the max-age
value of the Cache-Control
header is used. If both s-maxage
and max-age
are found, then s-maxage
is preferred. The max-age
is also passed-through to any downstream clients including CDNs and browsers.
-
当上游镜像不包含
Cache-Control
头或者该值很低时,你可以配置minimumCacheTTL
来增加缓存持续时间。¥You can configure
minimumCacheTTL
to increase the cache duration when the upstream image does not includeCache-Control
header or the value is very low. -
你可以配置
deviceSizes
和imageSizes
以减少可能生成的图片总数。¥You can configure
deviceSizes
andimageSizes
to reduce the total number of possible generated images. -
你可以将 formats 配置为禁用多种格式,转而使用单一图片格式。
¥You can configure formats to disable multiple formats in favor of a single image format.
minimumCacheTTL
你可以为缓存的优化图片配置生存时间 (TTL)(以秒为单位)。在许多情况下,最好使用 静态图片导入,它会自动散列文件内容并使用 immutable
的 Cache-Control
标头永久缓存图片。
¥You can configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a Static Image Import which will automatically hash the file contents and cache the image forever with a Cache-Control
header of immutable
.
module.exports = {
images: {
minimumCacheTTL: 60,
},
}
优化映像的过期时间(或更确切地说是最大期限)由 minimumCacheTTL
或上游映像 Cache-Control
标头(以较大者为准)定义。
¥The expiration (or rather Max Age) of the optimized image is defined by either the minimumCacheTTL
or the upstream image Cache-Control
header, whichever is larger.
如果你需要更改每个图片的缓存行为,你可以配置 headers
以在上游图片上设置 Cache-Control
标头(例如 /some-asset.jpg
,而不是 /_next/image
本身)。
¥If you need to change the caching behavior per image, you can configure headers
to set the Cache-Control
header on the upstream image (e.g. /some-asset.jpg
, not /_next/image
itself).
此时没有使缓存失效的机制,所以最好保持 minimumCacheTTL
为低电平。否则,你可能需要手动更改 src
属性或删除 <distDir>/cache/images
。
¥There is no mechanism to invalidate the cache at this time, so its best to keep minimumCacheTTL
low. Otherwise you may need to manually change the src
prop or delete <distDir>/cache/images
.
disableStaticImages
默认行为允许你导入静态文件(例如 import icon from './icon.png'
),然后将其传递给 src
属性。
¥The default behavior allows you to import static files such as import icon from './icon.png'
and then pass that to the src
property.
在某些情况下,如果此功能与期望导入行为不同的其他插件发生冲突,你可能希望禁用此功能。
¥In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.
你可以在 next.config.js
内禁用静态图片导入:
¥You can disable static image imports inside your next.config.js
:
module.exports = {
images: {
disableStaticImages: true,
},
}
dangerouslyAllowSVG
由于某些原因,默认 loader 不会优化 SVG 图片。首先,SVG 是一种矢量格式,这意味着它可以无损地调整大小。其次,SVG 具有许多与 HTML/CSS 相同的功能,如果没有适当的 内容安全策略 (CSP) 标头.5,可能会导致漏洞。
¥The default loader does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper Content Security Policy (CSP) headers.
因此,当已知 src
属性是 SVG 时,我们建议使用 unoptimized
属性。当 src
以 ".svg"
结尾时,这种情况会自动发生。
¥Therefore, we recommended using the unoptimized
prop when the src
prop is known to be SVG. This happens automatically when src
ends with ".svg"
.
但是,如果你需要使用默认图片优化 API 提供 SVG 图片,则可以在 next.config.js
中设置 dangerouslyAllowSVG
:
¥However, if you need to serve SVG images with the default Image Optimization API, you can set dangerouslyAllowSVG
inside your next.config.js
:
module.exports = {
images: {
dangerouslyAllowSVG: true,
contentDispositionType: 'attachment',
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
}
此外,强烈建议还设置 contentDispositionType
以强制浏览器下载图片,以及设置 contentSecurityPolicy
以阻止执行图片中嵌入的脚本。
¥In addition, it is strongly recommended to also set contentDispositionType
to force the browser to download the image, as well as contentSecurityPolicy
to prevent scripts embedded in the image from executing.
contentDispositionType
默认 loader 将 Content-Disposition
标头设置为 attachment
以增加保护,因为 API 可以提供任意远程图片。
¥The default loader sets the Content-Disposition
header to attachment
for added protection since the API can serve arbitrary remote images.
默认值为 attachment
,强制浏览器在直接访问时下载图片。当 dangerouslyAllowSVG
为真时,这一点尤为重要。
¥The default value is attachment
which forces the browser to download the image when visiting directly. This is particularly important when dangerouslyAllowSVG
is true.
你可以选择配置 inline
以允许浏览器在直接访问时渲染图片,而无需下载它。
¥You can optionally configure inline
to allow the browser to render the image when visiting directly, without downloading it.
module.exports = {
images: {
contentDispositionType: 'inline',
},
}
动画图片
¥Animated Images
默认 loader 将自动绕过动画图片的图片优化并按原样提供图片。
¥The default loader will automatically bypass Image Optimization for animated images and serve the image as-is.
尽力自动检测动画文件,并支持 GIF、APNG 和 WebP。如果你想明确绕过给定动画图片的图片优化,请使用 unoptimized 属性。
¥Auto-detection for animated files is best-effort and supports GIF, APNG, and WebP. If you want to explicitly bypass Image Optimization for a given animated image, use the unoptimized prop.
响应式图片
¥Responsive Images
默认生成的 srcset
包含 1x
和 2x
图片,以支持不同的设备像素比。但是,你可能希望渲染随视口延伸的响应式图片。在这种情况下,你需要设置 sizes
和 style
(或 className
)。
¥The default generated srcset
contains 1x
and 2x
images in order to support different device pixel ratios. However, you may wish to render a responsive image that stretches with the viewport. In that case, you'll need to set sizes
as well as style
(or className
).
你可以使用以下方法之一渲染响应式图片。
¥You can render a responsive image using one of the following methods below.
使用静态导入的响应式图片
¥Responsive image using a static import
如果源图片不是动态的,你可以静态导入以创建响应式图片:
¥If the source image is not dynamic, you can statically import to create a responsive image:
import Image from 'next/image'
import me from '../photos/me.jpg'
export default function Author() {
return (
<Image
src={me}
alt="Picture of the author"
sizes="100vw"
style={{
width: '100%',
height: 'auto',
}}
/>
)
}
试试看:
¥Try it out:
具有长宽比的响应式图片
¥Responsive image with aspect ratio
如果源图片是动态或远程 url,你还需要提供 width
和 height
来设置响应图片的正确宽高比:
¥If the source image is a dynamic or a remote url, you will also need to provide width
and height
to set the correct aspect ratio of the responsive image:
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}
/>
)
}
试试看:
¥Try it out:
带有 fill
的响应式图片
¥Responsive image with fill
如果你不知道宽高比,则需要设置 fill
属性并在父级上设置 position: relative
。或者,你可以根据所需的拉伸与裁剪行为设置 object-fit
样式:
¥If you don't know the aspect ratio, you will need to set the fill
prop and set position: relative
on the parent. Optionally, you can set object-fit
style depending on the desired stretch vs crop behavior:
import Image from 'next/image'
export default function Page({ photoUrl }) {
return (
<div style={{ position: 'relative', width: '300px', height: '500px' }}>
<Image
src={photoUrl}
alt="Picture of the author"
sizes="300px"
fill
style={{
objectFit: 'contain',
}}
/>
</div>
)
}
试试看:
¥Try it out:
主题检测 CSS
¥Theme Detection CSS
如果你想在浅色和夜间模式下显示不同的图片,你可以创建一个新组件,其中包含两个 <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} />
</>
)
}
import styles from './theme-image.module.css'
import Image from 'next/image'
const ThemeImage = (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:
getImageProps
对于更高级的用例,你可以调用 getImageProps()
来获取将传递给底层 <img>
元素的 props,然后将它们传递给另一个组件、样式、画布等。
¥For more advanced use cases, you can call getImageProps()
to get the props that would be passed to the underlying <img>
element, and instead pass to them to another component, style, canvas, etc.
这也避免了调用 React useState()
,因此可以带来更好的性能,但它不能与 placeholder
属性一起使用,因为占位符永远不会被删除。
¥This also avoid calling React useState()
so it can lead to better performance, but it cannot be used with the placeholder
prop because the placeholder will never be removed.
主题检测图片
¥Theme Detection Picture
如果你想为亮色和暗色模式显示不同的图片,可以使用 <picture>
元素根据用户的 首选配色方案 显示不同的图片。
¥If you want to display a different image for light and dark mode, you can use the <picture>
element to display a different image based on the user's preferred color scheme.
import { getImageProps } from 'next/image'
export default function Page() {
const common = { alt: 'Theme Example', width: 800, height: 400 }
const {
props: { srcSet: dark },
} = getImageProps({ ...common, src: '/dark.png' })
const {
props: { srcSet: light, ...rest },
} = getImageProps({ ...common, src: '/light.png' })
return (
<picture>
<source media="(prefers-color-scheme: dark)" srcSet={dark} />
<source media="(prefers-color-scheme: light)" srcSet={light} />
<img {...rest} />
</picture>
)
}
艺术方向
¥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()
.
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
¥Background CSS
你甚至可以将 srcSet
字符串转换为 image-set()
CSS 函数来优化背景图片。
¥You can even convert the srcSet
string to the image-set()
CSS function to optimize a background image.
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>
)
}
已知的浏览器错误
¥Known Browser Bugs
此 next/image
组件使用浏览器原生 延迟加载,对于 Safari 15.4 之前的旧版浏览器,可能会回退到预加载。使用模糊占位符时,Safari 12 之前的旧版浏览器将回退到空占位符。当使用 width
/height
或 auto
的样式时,可能会在 Safari 15 之前的旧浏览器上导致 布局转变,而不会出现 保持纵横比。详细信息请参见 这个 MDN 视频。
¥This next/image
component uses browser native lazy loading, which may fallback to eager loading for older browsers before Safari 15.4. When using the blur-up placeholder, older browsers before Safari 12 will fallback to empty placeholder. When using styles with width
/height
of auto
, it is possible to cause Layout Shift on older browsers before Safari 15 that don't preserve the aspect ratio. For more details, see this MDN video.
-
狩猎 15 - 16.3 在加载时显示灰色边框。Safari 16.4 已修复此问题。可能的解决方案:
¥Safari 15 - 16.3 display a gray border while loading. Safari 16.4 fixed this issue. Possible solutions:
-
使用 CSS
@supports (font: -apple-system-body) and (-webkit-appearance: none) { img[loading="lazy"] { clip-path: inset(0.6px) } }
¥Use CSS
@supports (font: -apple-system-body) and (-webkit-appearance: none) { img[loading="lazy"] { clip-path: inset(0.6px) } }
-
如果图片位于首屏,则使用
priority
¥Use
priority
if the image is above the fold
-
-
火狐浏览器 67+ 在加载时显示白色背景。可能的解决方案:
¥Firefox 67+ displays a white background while loading. Possible solutions:
-
启用 AVIF
formats
¥Enable AVIF
formats
-
使用
placeholder
¥Use
placeholder
-
版本历史
¥Version History
版本 | 变化 |
---|---|
v15.0.0 | contentDispositionType 配置默认更改为 attachment 。 |
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 支持。 Wrapper <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 推出。 |