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

On my way to the 3D city model workshop in Bonn where I‘m presenting our latest @igeoFHNW #AugmentedReality App… https://t.co/8ghq4GfZW5
About 5 days, 7 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

Teaching #Python to 11-13-year-old girls was great fun today at the Swiss national future day (#zukunftstag).… https://t.co/1lDmWdl02D
About 1 week, 2 days ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @GeoPythonConf: Interested in joining GeoPython 2019? Register to the mailing list: https://t.co/ub3CU7L5WL #python #GeoPython #geospat…
About 2 weeks, 2 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