繁体   English   中英

检查透明度,GraphicsMagick node.js

[英]Check for transparency, 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
  }
});

您也可以尝试一下imagemagick

Snippet位于TypeScript中,并使用BPromise.promisify来提高可读性。

请注意,这适用于PNG,JPEG的预期方式(返回字符串true / false),但对于GIF,它将为您提供一个串联的“ true” |“ false”字符串(例如“ truetruefalse”,并在每帧应用alpha检查) 。

我还建议将.trim()应用于结果,以消除由imagemagick v0.x返回的潜在的无用空白。 时不时地

import * as imagemagick from 'imagemagick';
import * as BPromise from 'bluebird';

...
const opaqueAsync: any = BPromise.promisify(imagemagick.identify, {context: imagemagick});
const isOpaqueReturnValue: string = await opaqueAsync(['-format', '%[opaque]', picturePath]);
const isPicTransparent: boolean = 'false' === isOpaqueReturnValue.trim();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM