使用Node / gm将SVG字符串转换为PNG输出

5
我希望将一个SVG字符串转换为PNG格式并在浏览器中输出。我查看了几篇文章:
我可以输出PNG格式但无法输出SVG格式。我可以很好地将SVG写入文件,但无法流式传输。
这是我的代码:
var gm = require('gm');
var im = gm.subClass({ imageMagick: true });

var inputsvg = 'public/test.svg';
var inputpng = 'public/test.png';

// works
im(inputsvg).write(output, function(err){
  if (!err) console.log('image converted.');
});

// works
im(inputpng).write(output, function(err){
  if (!err) console.log('image converted.');
});


res.set('Content-Type', 'image/png'); 

// works
im(inputpng).stream(function (err, stdout, stderr) {
  stdout.pipe(res);
});

// does not work - no errors given.
im(inputsvg).stream(function (err, stdout, stderr) {
  stdout.pipe(res);
});
1个回答

9

Okay got it.

var svg = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><svg width="840" height="430"  xmlns="http://www.w3.org/2000/svg" version="1.1"><rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" /></svg>';

var buf = new Buffer(svg);
res.set('Content-Type', 'image/png');
gm(buf, 'svg.svg').stream('png', function (err, stdout, stderr) {
  stdout.pipe(res);
});

一些重要的要点:

  • 必须有xml行
  • 在svg标签中必须提供宽度和高度
  • stream()函数需要格式参数('png')

希望这能帮助到某些人。


非常感谢您!正是我所需要的。 - Zachary Olson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接