svg to png convertion with imagemagick in node.js

人盡茶涼 提交于 2019-12-23 15:44:57

问题


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?


回答1:


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.




回答2:


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();



回答3:


you can also use streams and pipe the result somewhere without storing the result as a temp file. Below is some sample code take from the github repo

var fs = require('fs');

im.resize({
  srcData: fs.readFileSync('kittens.jpg', 'binary'),
  width:   256,
  format:  'png'
}, function(err, stdout, stderr){
  if (err) throw err
  fs.writeFileSync('kittens-resized.png', stdout, 'binary');  // change this part
  console.log('resized kittens.jpg to fit within 256x256px')
});

btw: your acceptance rate is 0%




回答4:


You can also use svgexport (I'm its author):

var svgexport = require('svgexport');

svgexport.render({input: 'file.svg', output: 'file.png'}, callback);


来源:https://stackoverflow.com/questions/13845488/svg-to-png-convertion-with-imagemagick-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!