如何在 Node Jimp 中將影像轉換為灰度?


NodeJS – grayscale() 是一個內建函式,用於根據 0 到 100 之間的數值將影像顏色去飽和度轉換為灰色。灰度化基本上是將影像從其原始顏色轉換為灰色的過程。

語法

image.color([
   {apply: 'greyscale', params: [value], cb }
]);

grayscale() 引數定義

  • value – 它接收用於應用灰度化的引數值作為輸入。範圍為 0 到 100。

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

輸入影像

使用 Node JIMP – grayscale()

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

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

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

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

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

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

示例

const Jimp = require('jimp');

async function greyscale() { // Function name is same as of file name
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.grayscale ()
   .write('/home/jimp/greyscale.jpg');
}

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

輸出

使用 Node JIMP – 帶 'cb' 引數的 grayscale()

示例

const Jimp = require('jimp') ;

async function greyscale() {
   // Reading Image
   const image = await Jimp.read
   ('/home/jimp/tutorials_point_img.jpg');
   image.color([{apply:'greyscale', params: [90]}], function(err){
      if (err) throw err;
   })
   .write('/home/jimp/greyscale.jpg');
}

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

輸出

更新於:2021年4月27日

1K+ 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.