在Node.js中读取PNG图像

时间:2012-06-28 15:21:02

标签: node.js png

在Node.js中有一种简单的方法来读取PNG文件并获取图像的像素吗?像node-image这样的东西,但另一种方式:)

我浏览了https://github.com/joyent/node/wiki/modules#wiki-graphics中列出的库,但它们是围绕命令行工具的简单包装器,提供裁剪和调整大小或复杂的绘图工具,如node-canvas

3 个答案:

答案 0 :(得分:20)

这个没有本机依赖性的PNG解码和编码:

pngjs - PNG encoder/decoder for Node.js with no native dependencies.

反转PNG颜色的示例:

var fs = require('fs'),
PNG = require('pngjs').PNG;

fs.createReadStream('in.png')
  .pipe(new PNG())
  .on('parsed', function() {

    for (var y = 0; y < this.height; y++) {
        for (var x = 0; x < this.width; x++) {
            var idx = (this.width * y + x) << 2;

            // invert color
            this.data[idx] = 255 - this.data[idx];
            this.data[idx+1] = 255 - this.data[idx+1];
            this.data[idx+2] = 255 - this.data[idx+2];

            // and reduce opacity
            this.data[idx+3] = this.data[idx+3] >> 1;
        }
    }

    this.pack().pipe(fs.createWriteStream('out.png'));
});

答案 1 :(得分:16)

我快要疯了,但我发现了一个:

png.js ― A PNG decoder in JS for the canvas element or Node.js.

var PNG = require('png-js');

var myimage = new PNG('myimage.png');

var width  = myimage.width;
var height = myimage.height;

myimage.decode(function (pixels) {
    //Pixels is a 1D array containing pixel data
});

请注意它是 JavaScript。适用于浏览器 <canvas> Node.JS

除了widthheight之外,还有更多属性,请参阅this source

答案 2 :(得分:4)

我认为

var myimage = new PNG('myimage.png');

应该是

var myimage = new PNG.load('myimage.png');
相关问题