User Tools

Site Tools


Sidebar

General

Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm


Martin Christen

View Martin Christen's profile on LinkedIn


Twitter

Timeline of @MartinChristen

MartinChristen avatar

RT @TFConsult: Celebrating 100th birthday of #physicist #RichardFeynman: The marvellous #Feynman lectures on #physics: https://t.co/81as7mN
About 1 week, 4 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @sergerey: Had a fantastic time giving our workshop on Spatial Data Science with PyData at @GeoPythonConf with @levijohnwolf. Looking f…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @fridex: Everything has an end even such an excellent conference #GeoPythonConf in Basel. Thanks to organizers for such an outstanding c…
About 1 week, 5 days ago by: Martin Christen (@MartinChristen)
node:tutorial07

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 https://github.com/pkrumins/node-png

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