【问题标题】:Check for transparency, GraphicsMagick node.js检查透明度,GraphicsMagick node.js
【发布时间】:2016-05-26 09:47:56
【问题描述】:

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

【问题讨论】:

标签: node.js png transparency alpha graphicsmagick


【解决方案1】:

我不确定您是否可以仅使用 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
  }
});

【讨论】:

  • 我试过了,效果很好。但是我怎样才能改变像素颜色/值。如果我将其更改为“this.data[idx]=0”,则会出错。
  • @KumarRavi 好吧,它不应该抛出错误。查看文档中有关如何更改“像素”并保存新图像的示例 - github.com/niegowski/node-pngjs#example
【解决方案2】:

你也可以试试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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-08
    • 2017-02-15
    • 2014-09-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多