如何替换图像中除黑色以外的所有颜色 Node.JS
How to replace all colours except black in image 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, 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");
});
此代码输出:
输入图像是:
我看过像 replace-color 这样的软件包,但这些软件包似乎旨在替换一种颜色,而不是全部,而只是一种颜色。非常感谢任何帮助
问题是我正在将格式从 png 更改为 jpg。将其保留为 png 可以解决问题
我正在尝试创建图像的轮廓。我已经将背景设为黑色,但我无法将所有其他颜色转换为灰色。
到目前为止我的代码:
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");
});
此代码输出:
输入图像是:
我看过像 replace-color 这样的软件包,但这些软件包似乎旨在替换一种颜色,而不是全部,而只是一种颜色。非常感谢任何帮助
问题是我正在将格式从 png 更改为 jpg。将其保留为 png 可以解决问题