我想将一个简单的动态svg片段转换为服务器上的PNG数据URI。像这样:
Config
我见过使用imagemagick和一些phantomJS变种的例子,但我正在寻找node.js中的动态动态解决方案,最好没有I / O.
答案 0 :(得分:12)
以下是使用Fabric.js:
的方法第1步:安装Cairo和node-canvas:
(我在Ubuntu 14.04上,可以找到其他操作系统的说明here。)
sudo apt-get update
sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
sudo npm install canvas
第2步:安装Fabric.js:
sudo npm install fabric
第3步:使用node
运行以下JavaScript:
var fabric = require('fabric').fabric;
var canvas = new fabric.createCanvasForNode(100, 100);
var svgStr = '<svg height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>';
fabric.loadSVGFromString(svgStr, function(objects, options) {
var obj = new fabric.PathGroup(objects, options);
canvas.add(obj);
console.log('<img src="' + canvas.toDataURL() + '" />');
});
结果:
(Ran on node v0.10.25。)
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAABmJLR0QA/wD/AP+gvaeTAAAHD0lEQVR4nO2dW2wVRRjHf6XSFgq1BUEoIiCXKih4jYmGxAR8MBa5RQloDD7wAA/og8EHfdAXEowm8oCGJxQviXhJjKkEUSgKeIkoohYLCCggt0JbwBah9vNhdnt2z57LbDl7dujOL/nSmZOzZ2e+/+52d+abb8FisVgsFovFYrFYLImmJO4GaDIAmAZMBCY5f8cCA4FKoBrVl26gHfgH6AAOAfsd2wfsATqL2/RwmCrINcB04AHH7gXKC/C7/wLfAo3AVmAH0FWA3+2TlAAzgfVAGyBFsFZnfzMx5OA0oRGlwALgOWBqpi+UAFOA24DJQJ1jg4AK1PXMpRO4CFwAmoHfgb2oa1UTSoUs7AZWARtQl77EUQo8gfJX4OgdBbIM5AOQUyBSADsJ8j7IUpDa7GdNE7DIaV9imI46aH3OqABZALIRpKtAImSzLpAGkMdAyjMLsxu4Pyb/FI3rgbdQl4SezteAvAByOmIRst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C3BCuXYnkMDAuVT2PGtrKmTBN9wy5BOx0K40hG5ZUGv3V7WhkrwsT5LDNLXwVYqMksy1nNTNhBNnqFj7FJirMx2Wgwf/RFp3twgjyDc7zyAlgY4gNk0gDcDpV/QO1bDwvYQQR4F238naIDZNImn/egVzpHlPY6PcISIt+F9Rc+n6dbcNGv+9FZSygE1gdcuOk8Bq+pQg70RSjt8zFCSCuQmVfizuw2SQ7TSBj0Kwwzu3NCqpPcJ44zwFv9OIH+jJrUHnOHZoI3GxFw5OQyod1xIAj0wQ7BDLAf3YsLIYYoIZSmt0d23XqytLWqTdR5FUb0/Hk3/3MAIfEaWkrprqJKQmzzXWCurFJy3US22OazQYEMtsvRqzZgMDmy/KKEXu+LJdXIJW1+kMDHFUM20Ag+/WqWFXwYHMuwvcYlHMRbFZSo7KSuowD/sZpaDUqsVfcDiykbUY9DJOyv/CsnzGRpGW2virSjSch9/tx4I4YfRyaMXgSnQHyCMgZA5wbxlpA6v1CCCq6pzZrzw2mL74/ZAcxP/hdKaXAi8B/eDpWD/KnAU7PZIcznxVdTj/6zHol+w4qA7FvaTOUjO8xLAeZB/IxyMWIRegE+QhkLsl+j6GXnG/6rEFNfL0JcqxAIhwFWQeyKPPZ4Fqsb/o06V24K1Bv6MnIFOBWYDwqO8J4YCgqkUENKiypEzUX0IoaAz+AilA7APyKE7+UnZ+Al0nwu3AzMQaVhvZHsh/BhbRdzv7yprxIOiWop+AVwOeo5cSFEKAD2AQ8i6GZpky4ZOlQgXLgJGCiY2OBao+Vo+LT2lFrU9tQSzT2o5b67QN+xhfDZrFYLBaLxWKxWCyW/wE2/OPNbPdQBAAAAABJRU5ErkJggg==" />
<子>
特别感谢fabric.loadSVGFromString
示例的this question。
子>
答案 1 :(得分:1)
看看svg-to-img。
它依赖于headless Chrome来进行转换。
要在项目中使用svg-to-img,请运行:
npm install svg-to-img
以下是将svg
转换为base64编码png
的方法:
const svgToImg = require("svg-to-img");
(async () => {
const svg = "<svg xmlns='http://www.w3.org/2000/svg'/>";
const png = await svgToImg.from(svg).toPng({ encoding: "base64" });
console.log("data:image/png;base64," + png);
})();
免责声明:我是svg-to-img的作者。