Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

svg to png convertion with imagemagick in node.js

I am search a way in nodejs to convert an svg to png with the help of imagemagick https://github.com/rsms/node-imagemagick, without storing the resulting png in a temp file on the local filesystem.

Unfortunately, I am unable to do this. And I didn't find example in the internet. Can someone give me an example?

like image 356
David Graf Avatar asked Dec 03 '25 17:12

David Graf


2 Answers

var im = require('imagemagick');
var fs = require('fs');
im.convert(['foo.svg', 'png:-'], 
function(err, stdout){
  if (err) throw err;
  //stdout is your image
  //just write it to file to test this:
   fs.writeFileSync('test.png', stdout,'binary');
});

It just throws the 'raw' arguments to the command line convert, so for any more questions, just look at convert's docs.

like image 112
Wrikken Avatar answered Dec 06 '25 08:12

Wrikken


oI found what I am looking for. Basically, I figured out how to pipe data into the std::in of the convert execution. This makes it possible for me to convert images without accessing the local file system.

Here is my demo code:

var im = require('imagemagick');
var fs = require('fs');

var svg = fs.readFileSync('/somepath/svg.svg', 'utf8');                

var conv = im.convert(['svg:-', 'png:-'])
conv.on('data', function(data) {
  console.log('data');
  console.log(data);
}); 
conv.on('end', function() {
  console.log('end');
});                                                                                
conv.stdin.write(svg);
conv.stdin.end();
like image 37
David Graf Avatar answered Dec 06 '25 07:12

David Graf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!