Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a PNG image in Node.js

Tags:

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 at https://github.com/joyent/node/wiki/modules#wiki-graphics, but they are either simple wrappers around command line tools providing cropping and resizing or complex drawing tools like node-canvas.

like image 912
Jan Špaček Avatar asked Jun 28 '12 15:06

Jan Špaček


People also ask

How do I read a PNG file in node?

I think the best way is fs. readFile (err, data) -> image = new PNG(data) .

Is Node JS good for image processing?

Node. js has an ecosystem of libraries you can use to process images, such as sharp, jimp, and gm module.


2 Answers

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]; // R             this.data[idx+1] = 255 - this.data[idx+1]; // G             this.data[idx+2] = 255 - this.data[idx+2]; // B              // and reduce opacity             this.data[idx+3] = this.data[idx+3] >> 1;         }     }      this.pack().pipe(fs.createWriteStream('out.png')); }); 
like image 119
P.D.P. Avatar answered Oct 12 '22 01:10

P.D.P.


I was about to became mad searching, but I found one:

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 }); 

Please note it's pure JavaScript. Works both in the browser <canvas> and in Node.JS.

There are more properties apart from width and height, see this source.

like image 20
Alba Mendez Avatar answered Oct 12 '22 02:10

Alba Mendez