Convert SVG to image (JPEG, PNG, etc.) in the browser

前端 未结 9 1048
春和景丽
春和景丽 2020-11-21 23:38

I want to convert SVG into bitmap images (like JPEG, PNG, etc.) through JavaScript.

相关标签:
9条回答
  • 2020-11-22 00:10

    change svg to match your element

    function svg2img(){
        var svg = document.querySelector('svg');
        var xml = new XMLSerializer().serializeToString(svg);
        var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
        var b64start = 'data:image/svg+xml;base64,';
        var image64 = b64start + svg64;
        return image64;
    };svg2img()
    
    0 讨论(0)
  • 2020-11-22 00:11

    Here a function that works without libraries and returns a Promise:

    /**
     * converts a base64 encoded data url SVG image to a PNG image
     * @param originalBase64 data url of svg image
     * @param width target width in pixel of PNG image
     * @return {Promise<String>} resolves to png data url of the image
     */
    function base64SvgToBase64Png (originalBase64, width) {
        return new Promise(resolve => {
            let img = document.createElement('img');
            img.onload = function () {
                document.body.appendChild(img);
                let canvas = document.createElement("canvas");
                let ratio = (img.clientWidth / img.clientHeight) || 1;
                document.body.removeChild(img);
                canvas.width = width;
                canvas.height = width / ratio;
                let ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                try {
                    let data = canvas.toDataURL('image/png');
                    resolve(data);
                } catch (e) {
                    resolve(null);
                }
            };
            img.src = originalBase64;
        });
    }
    

    On Firefox there is an issue for SVGs without set width / height.

    See this working example including a fix for the Firefox issue.

    0 讨论(0)
  • 2020-11-22 00:16

    This seems to work in most browsers:

    function copyStylesInline(destinationNode, sourceNode) {
       var containerElements = ["svg","g"];
       for (var cd = 0; cd < destinationNode.childNodes.length; cd++) {
           var child = destinationNode.childNodes[cd];
           if (containerElements.indexOf(child.tagName) != -1) {
                copyStylesInline(child, sourceNode.childNodes[cd]);
                continue;
           }
           var style = sourceNode.childNodes[cd].currentStyle || window.getComputedStyle(sourceNode.childNodes[cd]);
           if (style == "undefined" || style == null) continue;
           for (var st = 0; st < style.length; st++){
                child.style.setProperty(style[st], style.getPropertyValue(style[st]));
           }
       }
    }
    
    function triggerDownload (imgURI, fileName) {
      var evt = new MouseEvent("click", {
        view: window,
        bubbles: false,
        cancelable: true
      });
      var a = document.createElement("a");
      a.setAttribute("download", fileName);
      a.setAttribute("href", imgURI);
      a.setAttribute("target", '_blank');
      a.dispatchEvent(evt);
    }
    
    function downloadSvg(svg, fileName) {
      var copy = svg.cloneNode(true);
      copyStylesInline(copy, svg);
      var canvas = document.createElement("canvas");
      var bbox = svg.getBBox();
      canvas.width = bbox.width;
      canvas.height = bbox.height;
      var ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, bbox.width, bbox.height);
      var data = (new XMLSerializer()).serializeToString(copy);
      var DOMURL = window.URL || window.webkitURL || window;
      var img = new Image();
      var svgBlob = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
      var url = DOMURL.createObjectURL(svgBlob);
      img.onload = function () {
        ctx.drawImage(img, 0, 0);
        DOMURL.revokeObjectURL(url);
        if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob)
        {
            var blob = canvas.msToBlob();         
            navigator.msSaveOrOpenBlob(blob, fileName);
        } 
        else {
            var imgURI = canvas
                .toDataURL("image/png")
                .replace("image/png", "image/octet-stream");
            triggerDownload(imgURI, fileName);
        }
        document.removeChild(canvas);
      };
      img.src = url;
    }
    
    0 讨论(0)
提交回复
热议问题