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

I just signed up as @europython volunteer. Still many spaces available! Do it now! https://t.co/Bam6ZJCjFR
About 1 day, 23 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

@Mr_Robinini I will do a talk about this at @EuroSciPy in August...
About 2 days, 22 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

@Mr_Robinini Try jupyterhub, you can start jupyterlab too (change config file). https://t.co/kDKr9oV946
About 2 days, 22 hours 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