跳到內容
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