Convertissez SVG en Image (JPEG, PNG,etc.) dans le navigateur

je veux convertir SVG en images bitmap (comme JPEG, PNG, etc.) à l'aide de JavaScript.

249
demandé sur Phrogz 2010-10-20 11:13:48

5 réponses

Voici comment vous pouvez le faire par JavaScript:

  1. utilisez la bibliothèque JavaScript canvg pour rendre L'image SVG en utilisant Canvas: https://github.com/gabelerner/canvg
  2. capturer un URI de données encodé comme un JPG (ou PNG) à partir de la toile, selon ces instructions: capturer HTML Canvas comme gif/jpg/png / pdf?
212
répondu jbeard4 2017-05-23 12:02:59

jbeard4 solution a fonctionné à merveille.

j'utilise Raphael SketchPad pour créer un SVG. Lien vers les fichiers de l'étape 1.

pour un bouton de sauvegarde (id de svg est "editor", id de canvas est "canvas"):

$("#editor_save").click(function() {

// the canvg call that takes the svg xml and converts it to a canvas
canvg('canvas', $("#editor").html());

// the canvas calls to output a png
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("image/png");
// do what you want with the base64, write to screen, post to server, etc...
});
39
répondu coop 2013-07-10 09:56:06

Cela semble fonctionner dans la plupart des navigateurs:

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;
}
4
répondu worstenbrood 2017-06-26 21:40:59

Voici une solution Côté Serveur Basée sur PhantomJS. Vous pouvez utiliser JSONP pour faire un appel de domaine croisé au service image:

https://github.com/vidalab/banquo-server

par exemple:

http://[host]/api/https%3A%2F%2Fvida.io%2Fdocuments%2FWgBMc4zDWF7YpqXGR/viewport_width=980&viewport_height=900&delay=5000&selector=%23canvas

puis vous peut afficher l'image avec la balise img:

<img src="data:image/png;base64, [base64 data]"/>

il fonctionne à travers le navigateur.

2
répondu Phuoc Do 2015-06-04 07:10:04

si vous ne voulez pas dire programmatically, cette question devrait probablement appartenir à superuser.com.

dans les deux cas, la Boîte À Outils batik SVG peut être utile, en particulier la Rasterizer SVG .

-1
répondu William Niu 2010-10-20 07:17:28