Node.js程序员

Node.js 两种方法在本地实现 SVG to Image

2019-04-15  本文已影响7人  陈陌Chemo

canvg2.0

原址

https://github.com/canvg/canvg

获取

npm install canvg@2.0.0-beta.1 canvas@^2 jsdom@^13 xmldom@^0

使用
const fs = require('fs');
const canvg = require('canvg');
const { createCanvas } = require('canvas'); // 使用 npm i canvas 来获取

const inputName = 'test.svg';
const outputName = inputName.replace('.svg','.png');
try{
    (async() => {
        fs.readFile(inputName ,'utf-8', function(err, data) {
            if (err) {
                // 读取文件失败
                throw err;
            }
            const canvas = createCanvas();
            canvg(canvas, data.toString(), {
                ignoreMouse: true,
                ignoreAnimation: true,
                renderCallback: function () {
                    var base64Data = canvas.toDataURL('image/png').replace(/^data:image\/\w+;base64,/, "");
                    var dataBuffer = new Buffer.from(base64Data, 'base64');
                    fs.writeFile(outputName, dataBuffer, function(err) {
                        if (err) {
                            throw err;
                        }
                        console.log(`output file name : ${outputName}`);
                    });
                }
            });
        });
    })();
}
catch{
    console.log('args error');
}
注意
// if (svg.ImagesLoaded()) {
//  waitingForImages = false;
//  draw();
// }
var drawInvlID = setInterval(function () {
    if (svg.ImagesLoaded()) {
        waitingForImages = false;
        draw();
        clearTimeout(drawInvlID);
    }
}, 1);
// var a = (s || '').match(/-?(\d+(\.\d+)?|\.\d+)(?=\D|$)/gm) || [];
var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');

使用 convert-svg-to-png

原址

https://github.com/neocotic/convert-svg/tree/master/packages/convert-svg-to-png

获取

npm install --global convert-svg-to-png

使用
const convertFile = require('convert-svg-to-png');
const args = process.argv.slice(2);
try{
  (async() => {
    const outputFilePath = await convertFile(args[0],{"width":args[1],"height":args[2]});    
    console.log(`outputFilePath:${outputFilePath}`);
  })();
}
catch{
  console.log('args error');
}
注意
上一篇下一篇

猜你喜欢

热点阅读