dandroid dandroid - 8 months ago 38
Node.js Question

nodejs pixel manipulation library

Is there a library for nodejs that allows you to get and set the pixels of an image?


img = loadImg("myImg");
pix = img.getPixel(x, y);
img.setPixel(x, y, {R: 0, G: 0, B: 0});

PNG or JPEG extensions are good.

My research:

  • png-js - allows you to decode (ONLY decode) a png image, so no write

  • GraphicsMagick - allows a bunch of fancy operations but
    no pixel level access.

  • node-png - apparently allows writing a png given pixel data. (i
    didn't manage to install it though)

  • canvas - perhaps has something similar to what i need but it
    relies on cairo and pulls in a lot of stuff that is just not
    necessary (plus, i am having difficulties getting it to work)

I could not find this very simple functionality in ONE library. Do you happen to know if there exists such functionality? Thank you.


This one does both PNG decoding, encoding, and allows pixel manipulation without native dependencies:

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

An example for inverting the colors of a PNG (from the github readme):

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

  .pipe(new PNG({
      filterType: 4
  .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;