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

标签 node.js typescript image image-processing silhouette

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

到目前为止我的代码:

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, 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 可以解决问题

关于node.js - 如何替换图像Node.JS中除黑色以外的所有颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63693201/

相关文章:

php - 图片上传后无法显示

image - 测量两条线之间的距离

javascript - 我用 GIMP 和 mtPaint 调整了大小,它不起作用。放幻灯片时图像大小没有改变

node.js - 蒙戈JS : MongoError: failed to connect to server with correct credentials

node.js - node-gyp 重建问题编译器

带参数的 typescript 枚举

arrays - 如何在 Typescript 4.0.3 中正确扩展数组原型(prototype)?

javascript - 测试用例失败后的 Jest 清理

javascript - Node 脚本中 eval() 的替代方案

javascript - React 网站有时不会在移动设备上全屏显示