Reading a PNG image in Node.js

后端 未结 3 1881
眼角桃花
眼角桃花 2021-01-30 18:14

Is there an easy way in Node.js to read a PNG file and get the pixels of the image? Something like node-image, but the other way :)

I went through the libraries listed a

3条回答
  •  礼貌的吻别
    2021-01-30 18:52

    This one does both PNG decoding and encoding without native dependancies:

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

    An example for inverting the colors of a 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'));
    });
    

提交回复
热议问题