如何替换图像Node.JS中除黑色以外的所有颜色

问题描述

我正在尝试创建图像的轮廓。我已经将背景设为黑色,但是我无法将所有其他颜色转换为灰色。

到目前为止,我的代码

import sharp from "sharp";
import jimp from "jimp";

sharp("input.png")
  .flatten()
  .toFile("output.jpg")
  .then(async (data) => {
    const image = await jimp.read("output.jpg");

    image.scan(0,image.bitmap.width,image.bitmap.height,(x,y,idx) => {
      if (image.bitmap.data[idx] >= 2) {
        image.bitmap.data[idx] = 86;
        image.bitmap.data[idx + 1] = 101;
        image.bitmap.data[idx + 2] = 115;
        image.bitmap.data[idx + 3] = image.bitmap.data[idx + 3];
      }
    });

    image.write("output.jpg");
  });

代码输出

result

输入的图像为:

enter image description here

我看过像replace-color这样的软件包,但这些软件包似乎旨在替换单一颜色,而不是全部替换一种颜色。任何帮助都非常感激

解决方法

问题是我将格式从png更改为jpg。保留为png可解决问题