iT邦幫忙

0

使用Chatgpt學Next.js : 如何使用 next/image 遠端圖片加載

  • 分享至 

  • xImage
  •  

在 Next.js 中,
import Image from 'next/image' 是用來加載和優化圖片的。
next/image 提供了自動圖片優化功能,
可以在加載時根據設備的大小和解析度提供最佳的圖片尺寸,並且支持懶加載,提升性能

基本用法

首先,從 next/image 中導入 Image 組件:


export default function Home() {
  return (
    <div>
      <h1>My Image</h1>
      <Image
        src="/images/my-image.jpg" // 本地圖片路徑
        alt="A description of the image"
        width={500} // 指定圖片寬度
        height={300} // 指定圖片高度
      />
    </div>
  );
}

遠端圖片加載

如果你想從外部來源加載圖片,需要先在 next.config.js 中配置允許的外部圖片域名:
ex:如果我要使用pexels遠程圖片

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.pexels.com',
      },
    ],
  }
};

export default nextConfig;

取得 Pexels 圖片的正確 URL

點擊圖片右鍵 選擇 copy image address

import styles from './about.module.css';
function AboutPage() {
  return (
    <div className={styles.imgContainer}>
      <div>
        <Image
          src='https://images.pexels.com/photos/28874283/pexels-photo-28874283/free-photo-of-minimal-workspace-with-laptop-and-coffee-mug.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'
          alt='about'
          layout='responsive'
          width={50}
          height={100}
          objectFit='cover'
        />
      </div>
    </div>
  );
}

export default AboutPage;

解釋:

  • remotePatterns 允許你更靈活地控制圖片的遠程 URL。
    你可以不僅指定域名(hostname),還可以指定協議(protocol)、路徑(pathname)等。
  • 這種方式適合在你需要允許某個域名的特定部分(比如特定路徑或協議)的時候使用。它提供了更多的過濾條件。
  • 例如,如果你想允許 Pexels 的圖片,只允許來自 https 協議的圖片,你可以用 remotePatterns 來進行這種精細的控制。

也可以只設定 domains

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
        domains: ['images.pexels.com'],
  }
};

export default nextConfig;

注意事項

  • 確保正確的圖片 URL:遠程圖片的 URL 必須正確,並且包含在你允許的域名列表中。
  • 寬度和高度:next/image 需要指定圖片的 width 和 height,你可以根據實際需求來調整這些參數。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言