如何在 Node Jimp 中使用 crop() 函式裁剪影像?


NodeJS – crop() 是一個內建函式,用於裁剪影像。我們可以使用 crop 在指定的座標和尺寸內選擇/裁剪影像。

語法

crop( x, y, w, h, cb )

crop() 引數定義

  • x – 它將儲存裁剪的 x 座標值。(必需)

  • y – 它將儲存裁剪的 y 座標值。(必需)

  • w – 此引數用於儲存裁剪影像的寬度。(必需)

  • h – 此引數用於儲存裁剪影像的高度。(必需)

  • cb – 這是一個可選引數,可以在編譯完成後呼叫。

輸入影像

使用 Node JIMP – CROP()

在使用 crop() 函式之前,請檢查以下語句是否已執行以設定環境。

  • npm init -y // 初始化 Node 環境

  • npm install jimp --save // 安裝 jimp 依賴項

  • 建立一個 crop.js 檔案並將以下程式碼片段複製貼上到其中。

  • 使用 node crop.js 執行程式碼。

注意 - 方法名稱應與 JS 檔名匹配。只有這樣才能呼叫所需的方法。

示例

const Jimp = require('jimp') ;

async function crop() { // Function name is same as of file name
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.crop(100, 50, 470, 270)
   .write('/home/jimp/crop.jpg');
}

crop(); // Calling the function here using async
console.log("Image is processed successfully");

輸出

使用 Node JIMP – 帶有 'cb' 可選引數的 CROP()

示例

const Jimp = require('jimp') ;

async function crop() {
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   // Checking if any error occurs while cropping
   image.crop(150, 0, 1000, 1800, function(err){
      if (err) throw err;
   })
   .write('/home/jimp/crop.jpg');
}

crop();
console.log("Image is processed successfully");

輸出

/home/jimp/ >> node crop.js // On running the above code snippet
Image is processed successfully
(node:194779) UnhandledPromiseRejectionWarning: RangeError [ERR_OUT_OF_RANGE]:
The value of "offset" is out of range. It must be >= 0 and <= 1119996.
Received 1120040
   at boundsError (internal/buffer.js:49:9)
   at Buffer.readUInt32BE (internal/buffer.js:192:5)
   at Jimp.<anonymous> (/home/jimp/node_modules/@jimp/plugincrop/dist/index.js:43:37)
   at scan (/home/jimp/node_modules/@jimp/utils/dist/index.js:53:9)
   at Jimp.scanQuiet
(/home/jimp/node_modules/@jimp/core/dist/index.js:1262:32)
   at Jimp.cropQuiet (/home/jimp/node_modules/@jimp/plugincrop/dist/index.js:42:12)

更新於:2021年4月27日

4K+ 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告