跳到内容

图像优化

Next.js 的 <Image> 组件扩展了 HTML 的 <img> 元素,提供了

  • 尺寸优化: 自动为每种设备提供尺寸合适的图片,使用 WebP 等现代图片格式。
  • 视觉稳定性: 在图片加载时自动防止 布局偏移
  • 更快的页面加载: 仅当图片进入视口时才使用原生浏览器延迟加载,并可选地提供模糊占位符。
  • 资产灵活性: 按需调整图片大小,即使是存储在远程服务器上的图片。

要开始使用 <Image>,请从 next/image 导入并在组件中渲染它。

app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return <Image src="" alt="" />
}

src 属性可以是本地远程图片。

🎥 观看: 了解更多关于如何使用 next/imageYouTube (9 分钟)

本地图片

您可以将静态文件(如图片和字体)存储在根目录中名为 public 的文件夹下。然后,代码可以从基本 URL (/) 引用 public 文件夹内的文件。

Folder structure showing app and public folders
app/page.tsx
import Image from 'next/image'
 
export default function Page() {
  return (
    <Image
      src="/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

如果图片是静态导入的,Next.js 将自动确定其固有 widthheight。这些值用于确定图片的宽高比,并防止图片加载时出现 累积布局偏移 (Cumulative Layout Shift)

app/page.tsx
import Image from 'next/image'
import ProfileImage from './profile.png'
 
export default function Page() {
  return (
    <Image
      src={ProfileImage}
      alt="Picture of the author"
      // width={500} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  )
}

远程图像

要使用远程图片,您可以为 src 属性提供一个 URL 字符串。

app/page.tsx
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 用于推断图片的正确宽高比,并避免图片加载时出现布局偏移。另外,您可以使用 fill 属性使图片填充父元素的大小。

为了安全地允许来自远程服务器的图片,您需要在 next.config.js 中定义一个支持的 URL 模式列表。请尽可能具体,以防止恶意使用。例如,以下配置将只允许来自特定 AWS S3 存储桶的图片

next.config.ts
import type { NextConfig } from 'next'
 
const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
        search: '',
      },
    ],
  },
}
 
export default config

API 参考

有关 Next.js Image 的完整功能集,请参阅 API 参考。