如何将base64 svg图像转换为base64图像png

时间:2017-10-18 16:01:15

标签: javascript

我有一个将图表转换为svg的代码。但我需要输出格式为PNG图像。 svgString2Image是返回编码的base64 svg的函数。我该怎么做?非常感谢你。

function svgString2Image( svgString, width, height, format, callback ) {
  //console.log("svgString",svgString)
    format ? format : 'png';

    var imgsrc = 'data:image/svg+xml;base64,'+ btoa( unescape( encodeURIComponent( svgString ) ) ); // Convert SVG string to data URL
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    canvas.width = width;
    canvas.height = height;

    var image = new Image();
    image.onload = function() {
        context.clearRect ( 0, 0, width, height );
        context.drawImage(image, 0, 0, width, height);

        canvas.toBlob( function(blob) {
            var filesize = Math.round( blob.length/1024 ) + ' KB';
            if ( callback ) callback( blob, filesize );
        });

    };
    ///****************************
  document.getElementById('my_image').src=imgsrc;
    return image.src = imgsrc;

}

http://plnkr.co/edit/lPhmuYywPCdjQrnwhQcH?p=preview

2 个答案:

答案 0 :(得分:3)

正如@ guest271314和我在评论中所述,当需要base64字符串canvas.toDataURL时,请使用canvas.toBlob。 image.onload也是异步的,所以不可能“返回”base64 png字符串。您必须使用回调(或Promise作为@ guest271314声明)。

function svgString2Image(svgString, width, height, format, callback) {
    // set default for format parameter
    format = format ? format : 'png';
    // SVG data URL from SVG string
    var svgData = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgString)));
    // create canvas in memory(not in DOM)
    var canvas = document.createElement('canvas');
    // get canvas context for drawing on canvas
    var context = canvas.getContext('2d');
    // set canvas size
    canvas.width = width;
    canvas.height = height;
    // create image in memory(not in DOM)
    var image = new Image();
    // later when image loads run this
    image.onload = function () { // async (happens later)
        // clear canvas
        context.clearRect(0, 0, width, height);
        // draw image with SVG data to canvas
        context.drawImage(image, 0, 0, width, height);
        // snapshot canvas as png
        var pngData = canvas.toDataURL('image/' + format);
        // pass png data URL to callback
        callback(pngData);
    }; // end async
    // start loading SVG data into in memory image
    image.src = svgData;
}

// call svgString2Image function
svgString2Image(svgString, 800, 600, 'png', /* callback that gets png data URL passed to it */function (pngData) {
    // pngData is base64 png string
});

答案 1 :(得分:1)

最后一个参数没有函数传递给svgString2Image。将函数传递给期望svgString2Imageblob参数的filesize