图片优化

next/image 是 Next.js 官方的 <img> 替代品,自动完成:

  • 尺寸优化:按设备分发合适尺寸 + WebP。
  • 视觉稳定:自动防止加载时的布局抖动(CLS)。
  • 更快首屏:懒加载 + 可选 blur 占位图。
  • 资源灵活:本地或远程图片都能按需缩放。

基本用法

import Image from 'next/image';

export default function Page() {
  return <Image src="/profile.png" alt="头像" width={500} height={500} />;
}

src 可以是本地路径或远程 URL。

本地图片

把静态资源放在根目录的 public/ 下,直接用 /xxx.png 引用。

推荐方式:静态 import,这样 widthheightblurDataURL 都会自动填上:

import Image from 'next/image';
import ProfileImage from './profile.png';

export default function Page() {
  return (
    <Image
      src={ProfileImage}
      alt="头像"
      // width / height / blurDataURL 自动提供
      placeholder="blur"
    />
  );
}

文件名不定?用动态 import

博客封面之类路径来自数据的场景,可以在服务端组件里用 import()

import Image from 'next/image';

async function PostImage({ imageFilename, alt }: { imageFilename: string; alt: string }) {
  const { default: image } = await import(`../content/blog/images/${imageFilename}`);
  return <Image src={image} alt={alt} />;
}

路径里必须带一个 静态前缀../content/blog/images/),Next.js 会把这个目录下所有文件打进产物,外部无法跳出该目录。

远程图片

远程 URL 要自己提供 width / height(或用 fill),因为构建期 Next.js 并不能访问远端图:

<Image
  src="https://s3.amazonaws.com/my-bucket/profile.png"
  alt="头像"
  width={500}
  height={500}
/>

同时需要在 next.config.ts 白名单中允许该域名,防止 URL 被滥用:

import type { NextConfig } from 'next';

const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        pathname: '/my-bucket/**',
      },
    ],
  },
};

export default config;

写得越具体越安全。

fill 模式

当你希望图片撑满父容器(父容器要 position: relative 且有尺寸):

<div style={{ position: 'relative', width: 320, height: 180 }}>
  <Image src="/cover.jpg" alt="封面" fill sizes="320px" />
</div>

sizes 帮 Next.js 选用最合适的响应式图源,务必提供。

性能建议

  • 首屏的关键图像priority,让它提前加载。
  • 列表缩略图 用合理的 sizes,浏览器才能选出最优尺寸。
  • 静态 import 能带来免费的 blur 占位,体验显著更好。
  • 不要对装饰性图标使用 Image,直接 <img> 或 SVG 更轻量。

圖片優化

next/image 是 Next.js 官方的 <img> 替代品,自動完成:

  • 尺寸優化:依裝置分發合適尺寸 + WebP。
  • 視覺穩定:自動防止載入時的版面抖動(CLS)。
  • 更快首屏:延遲載入 + 可選 blur 佔位圖。
  • 資源靈活:本地或遠端圖片皆可按需縮放。

基本用法

import Image from 'next/image';

export default function Page() {
  return <Image src="/profile.png" alt="頭像" width={500} height={500} />;
}

src 可為本地路徑或遠端 URL。

本地圖片

把靜態資源放在根目錄 public/ 下,直接以 /xxx.png 引用。

建議做法:靜態 importwidthheightblurDataURL 都會自動填入:

import Image from 'next/image';
import ProfileImage from './profile.png';

export default function Page() {
  return (
    <Image
      src={ProfileImage}
      alt="頭像"
      // width / height / blurDataURL 自動提供
      placeholder="blur"
    />
  );
}

檔名不定?用動態 import

網誌封面這類路徑來自資料的情境,可在伺服器元件中使用 import()

import Image from 'next/image';

async function PostImage({ imageFilename, alt }: { imageFilename: string; alt: string }) {
  const { default: image } = await import(`../content/blog/images/${imageFilename}`);
  return <Image src={image} alt={alt} />;
}

路徑需帶 靜態前綴../content/blog/images/),Next.js 會把該目錄下所有檔案打包,外部無法跳出此目錄。

遠端圖片

遠端 URL 必須自行提供 width / height(或使用 fill),因建置期 Next.js 無法存取遠端檔:

<Image
  src="https://s3.amazonaws.com/my-bucket/profile.png"
  alt="頭像"
  width={500}
  height={500}
/>

另外需在 next.config.ts 白名單允許此網域,避免 URL 被濫用:

import type { NextConfig } from 'next';

const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        pathname: '/my-bucket/**',
      },
    ],
  },
};

export default config;

寫得愈具體愈安全。

fill 模式

當你希望圖片填滿父容器(父容器需 position: relative 並有尺寸):

<div style={{ position: 'relative', width: 320, height: 180 }}>
  <Image src="/cover.jpg" alt="封面" fill sizes="320px" />
</div>

sizes 有助 Next.js 選擇最合適的響應式圖源,務必提供。

效能建議

  • 首屏關鍵圖像priority,讓它優先載入。
  • 清單縮圖 指定合理的 sizes,瀏覽器才能挑出最佳尺寸。
  • 靜態 import 可帶來免費 blur 佔位,體驗顯著更佳。
  • 勿對裝飾性圖示使用 Image,直接 <img> 或 SVG 更輕量。

Image Optimization

next/image replaces the HTML <img> element and gives you:

  • Size optimization: correctly sized images for each device, modern formats like WebP.
  • Visual stability: prevents layout shift (CLS) while images load.
  • Faster loads: native lazy loading with optional blur-up placeholders.
  • Asset flexibility: on-demand resizing, even for remote images.

Basic usage

import Image from 'next/image';

export default function Page() {
  return <Image src="/profile.png" alt="Profile" width={500} height={500} />;
}

src can be a local path or a remote URL.

Local images

Drop assets into public/ at the project root and reference them as /xxx.png.

The best experience is a static importwidth, height, and blurDataURL are inferred automatically:

import Image from 'next/image';
import ProfileImage from './profile.png';

export default function Page() {
  return (
    <Image
      src={ProfileImage}
      alt="Profile"
      // width / height / blurDataURL inferred
      placeholder="blur"
    />
  );
}

Filenames not known statically?

For things like blog cover images coming from data, use dynamic import() inside a Server Component:

import Image from 'next/image';

async function PostImage({ imageFilename, alt }: { imageFilename: string; alt: string }) {
  const { default: image } = await import(`../content/blog/images/${imageFilename}`);
  return <Image src={image} alt={alt} />;
}

The path must include a static prefix (../content/blog/images/). Next.js bundles every file under that prefix, and external input can't escape it.

Remote images

For remote URLs you must supply width / height (or use fill) — Next.js can't access them at build time:

<Image
  src="https://s3.amazonaws.com/my-bucket/profile.png"
  alt="Profile"
  width={500}
  height={500}
/>

Whitelist the host in next.config.ts to prevent abuse:

import type { NextConfig } from 'next';

const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        pathname: '/my-bucket/**',
      },
    ],
  },
};

export default config;

Be as specific as possible.

fill mode

When you want the image to fill a sized, position: relative parent:

<div style={{ position: 'relative', width: 320, height: 180 }}>
  <Image src="/cover.jpg" alt="Cover" fill sizes="320px" />
</div>

Always supply sizes so the browser can pick the best responsive source.

Performance tips

  • Add priority to the key above-the-fold image so it's loaded eagerly.
  • For thumbnails in lists, provide accurate sizes for proper source selection.
  • Static imports give you a free blur placeholder — noticeable UX boost.
  • Don't use <Image> for decorative icons; plain <img> or inline SVG is lighter.