Published on

Next Image 如何合理加载图片大小

Authors
  • avatar
    Name
    Shelton Ma
    Twitter

1. Image size

import Image from "next/image";

// 只给宽度, 等比例显示, 同时className约束大小
<Image
  src="/logo.png"
  alt="Logo"
  width={100}
  height={0}
  className="w-16 lg:w-32"
/>

// fill需要搭配父元素的relative 无需指定长宽, 只需在div中指定大小
// object-contain 不裁剪图片, 比例不对会留出div的背景 object-cover比例不对会裁剪
<div className="relative w-8 h-8">
  <Image
    src="/default-blue.png"
    alt="profiles"
    fill
    className="rounded-md object-contain"
  />
</div>

2. Image config, 外部图片需要配置

// next.config.mjs
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "mango.blender.org",
        port: "",
        pathname: "/wp-content/uploads/**",
      },
    ],
  },
};