Next.js 的 <Image> 组件扩展了 HTML 的 <img> 元素,以提供以下功能:
要开始使用 <Image>,请从 next/image 导入它并在组件中渲染。
import Image from "next/image";
export default function Page() {
return <Image src="" alt="" />;
}import Image from "next/image";
export default function Page() {
return <Image src="" alt="" />;
}🎥 观看: 了解如何使用
next/image→ YouTube (9 分钟)。
你可以将图片和字体等静态文件存储在根目录中名为 public 的文件夹下。public 文件夹中的文件可以通过以根 URL (/) 开头的路径在代码中引用。

import Image from "next/image";
export default function Page() {
return (
<Image
src="/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
);
}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 会自动确定其固有的 width 和 height。这些值用于确定图片的比例,并在图片加载时防止 累积布局偏移。
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
/>
);
}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 字符串。
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}
/>
);
}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 在构建过程中无法访问远程文件,你需要手动提供 width、height 以及可选的 blurDataURL 属性。width 和 height 用于推断图片的正确宽高比,并避免图片加载时引起的布局偏移。或者,你可以使用 fill 属性 使图片填充父元素的大小。
为了安全地允许来自远程服务器的图片,你需要在 next.config.js 中定义一个支持的 URL 模式列表。请尽量具体,以防止恶意使用。例如,以下配置将只允许来自特定 AWS S3 存储桶的图片:
import type { NextConfig } from "next";
const config: NextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "s3.amazonaws.com",
port: "",
pathname: "/my-bucket/**",
search: "",
},
],
},
};
export default config;module.exports = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "s3.amazonaws.com",
port: "",
pathname: "/my-bucket/**",
search: "",
},
],
},
};