簡體   English   中英

使用Node / gm將SVG字符串轉換為PNG輸出

[英]SVG string to PNG output using Node / gm

我想獲取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);
});

好,知道了。

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()函數需要format參數('png')

希望能幫助別人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM