Reputation: 15
Using GM (GraphicsMagick) in NodeJS I wanted to generate some image content via using loops with commands such as drawPoint to set pixel data however i am not sure on the best practice to do so.
The code i have tested with loops works however it is very slow since it loads and saves the image each time it sets a pixel.
Here is my test which generates random rgb noise. How can i temporarily store image data which is set via a loop and then save it only after it has finished?
var fs = require('fs');
var gm = require('gm').subClass({imageMagick: true});
var w = 200;
var h = 200;
gm(200, 200, '#ddff99f3').write('./Random Noise.png', function (err) {});
var row = 0;
var col = 0;
var r = 0;
var g = 0;
var b = 0;
function rgb(r, g, b){
r = Math.floor(r);
g = Math.floor(g);
b = Math.floor(b);
return ['rgb(',r,',',g,',',b,')'].join('');
}
for (row = 0; row < h; row++){
for (col = 0; col < w; col++){
r = Math.floor((Math.random() * 255) + 1);
g = Math.floor((Math.random() * 255) + 1);
b = Math.floor((Math.random() * 255) + 1);
gm('./Random Noise.png')
.fill(rgb(r,g,b))
.drawPoint(col, row)
.write('./Random Noise.png', function (err) {});
}
}
Upvotes: 1
Views: 579
Reputation: 24419
I don't know enough about node.js's gm to offer any answers, so this is more of an open comment to get you on the right path.
Use FX expressions
Faster then your solution, but still slow as each pixel will need to be evaluated.
convert -size 200x200 xc:'#ddff99f3' -fx 'rand()' 'Random Noise.png'
Build a raster image first.
It's way faster to populate 1d array of 8-bit values, and import them directly. Again, you'll have to checkout node-gm documents to see how they import/export data.
var raster = [],
index = 0;
for (row = 0; row < h; row++){
for (col = 0; col < w; col++) {
raster[index++] = Math.floor((Math.random() * 255) + 1) // RED
raster[index++] = Math.floor((Math.random() * 255) + 1) // GREEN
raster[index++] = Math.floor((Math.random() * 255) + 1) // BLUE
}
}
The CLI command to import this would be something like ...
cat raster.dat | convert -size 200x200 -depth 8 rgb:- 'Random Noise.png'
I imagine the docs would refer to the above as "streams" and "pipes".
Hopefully someone else would be able to offer node-gm examples.
Upvotes: 1