检查透明度,GraphicsMagick node.js

我正在制作一个用户可以上传图片的代码。 图像转换GraphicsMagick并上传到我们的云。 但是,如果非透明图像转换为JPG而不是透明图像的PNG,那将是最好的。 如何检查图像是否包含GraphicsMagick中的Alpha通道?

我不确定你只能使用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 } }); 

或者遍历像素并决定它是否对你有价值,或者你可以忽略它:

 ... .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 } }); 
Interesting Posts