如何在Edge中下载图像/png数据URI

How do you download a image/png data URI in Edge?

本文关键字:png 数据 URI 图像 下载 Edge      更新时间:2023-09-26

我正在尝试使用基于https://github.com/exupero/saveSvgAsPng和http://techslides.com/save-svg-as-an-image.SVG被转换为数据URI,并在画布中呈现为图像,画布被转换为PNG数据URI。此URI是使用锚标记作为文件下载的。我已经能够确认这在当前版本的FF、Chrome和Safari中工作;然而,在锚标记上触发下载会导致Edge挂起(控制台中只有doctype警告)或完全崩溃。有没有办法在Edge中实现这一点,或者还不完全支持数据URI的锚下载?

从以上来源创建的代码:

//this gets the svg and inlines all styles.  It has a property "source" as well as width and height of the SVG.
var svgDownload = getElementChildrenAndStyles(svgID);
var image = new Image();
image.onload = function () {
  var canvas = document.createElement('canvas');
  canvas.width = svgDownload.width;
  canvas.height = svgDownload.height;
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = "#FFFFFF";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(image, 0, 0);
  var a = document.createElement("a");
  a.download = "chart.png";
  try {
    console.log("converting canvas");
    a.href = canvas.toDataURL("image/png");
    console.log("canvas converted. triggering download");
    document.body.appendChild(a);
    a.addEventListener("click", function(e) {
      a.parentNode.removeChild(a);
    });
    a.click();
  }
  catch (e){
    //error handling
  }
};
try {
  console.log("making image source url");
  //both methods of creating the image source here work in most browsers except Edge
  //image.src = "data:image/svg+xml;base64," + btoa( svgDownload.source.join() );
  image.src = window.URL.createObjectURL(new Blob(svgDownload.source, {"type": 'image/svg+xml;base64'}));
  console.log("image source set");
}
catch (e){
  //error handling
}

意识到这是一个老问题,但对于其他人来说:Edge和IE不支持dataURL作为锚标记的href。不过它会接受它作为img标记的来源。我能想出的最好的解决方案是使用download.js下载文件。然而,您将遇到的下一个问题是,当您将图像标记的src设置为SVG以渲染PNG时,该image对象的"load"事件不会在Edge中触发。目前还没有办法解决这个问题。