如何在 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.