25 Jan 2014

Generate a PNG from Pixmap Array

Use node.js and the node-png (libpng) module to generate and manipulate a PNG. An RGB data buffer or pixmap is created programmatically and the result written to file as a PNG image.

Install the node-png module using npm:

$ npm install png

You may also need to install libpng:

$ sudo apt-get install libpng-dev

Edit server.js:

var http = require("http");
var fs = require("fs");
var Buffer = require("buffer").Buffer;
var Png = require("png").Png;

var IMAGE_WIDTH = 255;
var IMAGE_HEIGHT = 255;

var server = http.createServer(function(req, res) {

  var rgb_data = new Buffer(IMAGE_WIDTH * IMAGE_HEIGHT * 3);

  for(var h = 0; h < IMAGE_HEIGHT; h++)
  {
    for(var w = 0; w < IMAGE_WIDTH; w++)
    {
      var p = h * IMAGE_WIDTH * 3 + w * 3;
      rgb_data[p + 0] = h; // r (0-255)
      rgb_data[p + 1] = 0; // g (0-255)
      rgb_data[p + 2] = w; // b (0-255)
    }
  }

  var png = new Png(rgb_data, IMAGE_WIDTH, IMAGE_HEIGHT, "rgb")

  fs.writeFile("output.png", png.encodeSync().toString("binary"),
               "binary", function(err) {
    if(err) { throw err; }
    res.end("PNG image generated");
  });

}).listen(8080);

We use Buffer, a standard node.js class as our pixel map. In the case of RGB we require 3 value components for each pixel. We iterate over the buffer (array) setting the colour component values, then instantiate a new Png and write the image to file.

Start the node instance:

$ node server.js

Invoke using your browser:

http://localhost:8080
PNG image generated

Open output.png, which will be in your working directory:

$ eog output.png

output.png should look like this:

Generated PNG image from pixmap