有想到什麼再寫什麼,沒想到什麼就算了

node.js sharp套件使用說明

Sharp 是 Node.js 上一個高效的圖像處理套件,可用於縮放、裁剪、轉換格式、調整大小、銳化、調整對比度、亮度等操作。以下是 Sharp 套件的基本使用方法:

1. 安裝 Sharp

npm install sharp

2. 基本使用

const sharp = require('sharp');

// 讀取圖片
sharp('input.jpg')
  // 縮放圖片
  .resize(200, 200)
  // 儲存圖片
  .toFile('output.jpg')
  .then(() => {
    console.log('圖片處理完成');
  })
  .catch(err => {
    console.error('錯誤:', err);
  });

3. 縮放圖片

// 縮放至固定大小
sharp('input.jpg')
  .resize(200, 200)
  .toFile('output.jpg');

// 縮放至最大寬度或高度
sharp('input.jpg')
  .resize(null, 200) // 固定高度,寬度自適應
  .toFile('output.jpg');

// 縮放至最小寬度或高度
sharp('input.jpg')
  .resize(200, null) // 固定寬度,高度自適應
  .toFile('output.jpg');

// 維持比例縮放
sharp('input.jpg')
  .resize(200, 200)
  .withoutEnlargement() // 避免放大圖片
  .toFile('output.jpg');

4. 裁剪圖片

// 裁剪正方形區域
sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 200, height: 200 })
  .toFile('output.jpg');

// 裁剪特定區域
sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 200, height: 100 })
  .toFile('output.jpg');

// 裁剪中心區域
sharp('input.jpg')
  .resize(200, 200)
  .crop() // 自動裁剪中心區域
  .toFile('output.jpg');

5. 轉換格式

// 轉換為 PNG 格式
sharp('input.jpg')
  .toFormat('png')
  .toFile('output.png');

// 轉換為 WebP 格式
sharp('input.jpg')
  .toFormat('webp')
  .toFile('output.webp');

6. 調整大小

// 調整圖片大小
sharp('input.jpg')
  .resize(200, 200) // 縮放至 200x200
  .toFile('output.jpg');

// 調整圖片大小並填滿空白
sharp('input.jpg')
  .resize(200, 200)
  .extend({
    background: { r: 255, g: 255, b: 255, alpha: 1 }, // 填充白色背景
  })
  .toFile('output.jpg');

7. 銳化圖片

// 銳化圖片
sharp('input.jpg')
  .sharpen()
  .toFile('output.jpg');

// 自定義銳化參數
sharp('input.jpg')
  .sharpen({ sigma: 2, flat: 0.5, jagged: 0.5 }) // 調整銳化強度
  .toFile('output.jpg');

8. 調整對比度、亮度

// 調整對比度
sharp('input.jpg')
  .contrast(1.5) // 增加對比度
  .toFile('output.jpg');

// 調整亮度
sharp('input.jpg')
  .brightness(0.5) // 增加亮度
  .toFile('output.jpg');

9. 其他功能

Sharp 提供許多其他功能,例如:

  • 旋轉圖片
  • 鏡像圖片
  • 添加水印
  • 生成縮略圖
  • 添加邊框
  • 調整顏色

更多功能請參考官方文檔: https://sharp.pixelplumbing.com/

總結

Sharp 是一個功能強大、高效的 Node.js 圖像處理庫,可以輕鬆實現各種圖像操作。通過以上示例代碼,你應該能夠快速上手使用 Sharp。

提示