User Tools

Site Tools



Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm

Martin Christen

View Martin Christen's profile on LinkedIn


Timeline of @MartinChristen

MartinChristen avatar

@PostFinance If you are interested in Python - the @EuroPython conference, largest Python conf in Europe with over…
About 3 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @opengeospatial: OGC seeks public comment on update to GeoTIFF standard. This minor revision to GeoTIFF enables the use of newer coordin…
About 5 days, 12 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @europython: Early-bird tickets sold out in less than 10 minutes. Amazing ! Sales were so fast, we ended up selling 275 tickets instead…
About 6 days, 15 hours ago by: Martin Christen (@MartinChristen)

Node.js Tutorials - Part 0

Node.js Tutorial 7

Generating png images

Encoding png images is not part of node.js base, therefore we rely on plugins. While it would be possible to encode and decode png from JavaScript, I prefer using a module written in C++. One such module is “node-png”, available at

To install this 3rd party node-png module, npm can be used which is included in the node.js distribution.

npm install png

With this code an 512×512 RGB image is created and stored in a file.

var fs = require('fs');
var sys = require('sys');
var png = require('png').Png;

var width = 512;
var height = 512;

// create new array containing RGB data
var rgb = new Buffer(width*height*3);

// now fill the image
for (var i=0; i<height; i++) {
    for (var j=0; j<width; j++) {
        rgb[i*width*3 + j*3 + 0] = 128*i*j/255;
        rgb[i*width*3 + j*3 + 1] = 128*i*j/255;
        rgb[i*width*3 + j*3 + 2] = 0;

// create the png object
var myimage = new png(rgb, width, height, 'rgb');

// encode png to file:
fs.writeFileSync('output.png', myimage.encodeSync().toString('binary'), 'binary');

This results in an image file “output.png” which looks like this:


node/tutorial07.txt · Last modified: 2013/09/16 22:05 by mchristen