我正在编写一个代码,用户可以在其中上传图像。图像使用 GraphicsMagick 进行转换并上传到我们的云端。但最好将非透明图像转换为 JPG,而不是透明图像的 PNG。如何在 GraphicsMagick 中检查图像是否包含 Alpha channel ?
最佳答案
我不确定您是否可以仅使用 GraphicsMagick 来实现这一目标,但可以通过其他几种方式实现。例如 pngjs :
您可以检查 PNG 元数据:
const gm = require('gm');
const PNG = require('pngjs').PNG;
gm('/path/to/image')
.stream('png')
.pipe(new PNG({}))
.on('metadata', meta => {
if (meta.alpha) {
// image is transparent
} else {
// image is not transparent
}
});
或者迭代像素并确定它的透明度对您是否有值(value),或者您可以忽略它:
...
.on('parsed', function() {
let isAlphaValuable = false;
for (var y = 0; y < this.height; y++) {
for (var x = 0; x < this.width; x++) {
var idx = (this.width * y + x) << 2;
// this.data[idx] - red channel
// this.data[idx + 1] - green channel
// this.data[idx + 2] - blue channel
// this.data[idx + 3] - alpha channel
// if there is at least one pixel
// which transparent for more than 30%
// then transparency valuable to us
isAlphaValuable |= (1 - this.data[idx + 3] / 255) > 0.3;
}
}
if (isAlphaValuable) {
// keep transparency
} else {
// ignore transparency
}
});
关于node.js - 检查透明度,GraphicsMagick node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35410131/