node.js - 检查透明度,GraphicsMagick node.js

标签 node.js png transparency alpha graphicsmagick

我正在编写一个代码,用户可以在其中上传图像。图像使用 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/

相关文章:

javascript - 比较两个玩家分数数组,看看谁在列表中上升/下降

C# .svg 文件到 System.Drawing.Image

perl - 使用 Perl 和 GD 调整 PNG 大小时如何保持透明度

c++ - VTKPNGWriter 打印出黑色图像?

javascript - 带有外部蒙版透明fabricjs的蒙版对象

iphone - 带边框的透明按钮

node.js - 用于大数据并具有更多更新/删除操作的Elasticsearch索引架构

sql - 如何将现有的 NodeJS 服务器应用程序连接到 Azure SQL 数据库

visual-c++ - 立方体的一个面上的透明度 OpenScreenGraph

javascript - "await"函数的 "async"属性在实例后休眠 - Javascript