我尝试用 node + GraphicsMagick 交换 png 中的一种颜色。
我的代码:
const gm = require('gm');
gm('./in.png').fill('black').opaque('#ccffff').write('./out.png', (err) => {
console.log("recolored file saved");
});
此脚本不仅会更改图像的颜色,还会更改图像的内容!
如何只更改颜色?
答案 0 :(得分:1)
请注意,我确实理解这个问题,但是如果您使用 ImageMagick 执行以下操作,您会得到我所期望的:
magick image.png -fill magenta -opaque "rgb(204,255,255)" result.png
答案 1 :(得分:0)
这种在 gm(或 imagemagick)中无法实现的 1:1 颜色交换还有另一个概念(详情:https://legacy.imagemagick.org/Usage/color_basics/#replace)
但是您可以逐个像素地转换:
var fs = require('fs'),
PNG = require('pngjs').PNG;
console.log("run convert ...")
fs.createReadStream('./in.png')
.pipe(new PNG())
.on('parsed', function() {
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var idx = (this.width * y + x) << 2;
// exchange color
if(this.data[idx] == 204 && this.data[idx+1] == 255 && this.data[idx+2] == 255){
this.data[idx] = 255; // R
this.data[idx+1] = 0; // G
this.data[idx+2] = 0; // B
}
}
}
this.pack().pipe(fs.createWriteStream('out.png'));
});