如何使用Javascript/jQuery和C#将SVG转换为PNG以供下载?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (394)

在一页上有一个SVG图像,当用户单击一个链接,会调用这个链接以获取toDataUrl():

            console.log('Processing svg for NOT Internet Explorer');
            var svgText = $("#div-surrounding-svg-element").html();
            var d3Canvas = document.getElementById("d3-canvas");
            d3Canvas.width = 2000;
            d3Canvas.height = 300;
            var ctxt = d3Canvas.getContext("2d");
            // make canvas background
            ctxt.fillStyle = "#fff";
            ctxt.fillRect(0, 0, d3Canvas.width, d3Canvas.height);

            var svg = new Blob([svgText], { type: "image/svg+xml;charset=utf-8" });
            var domURL = self.URL || self.webkitURL || self;
            var url = domURL.createObjectURL(svg);
            var img = new Image();

            img.onload = function ()
            {
                ctxt.drawImage(this, 0, 0);
                domURL.revokeObjectURL(url);
                var dataUrl = d3Canvas.toDataURL();
                // $('#download-chart-dataUrl').val(dataUrl);
                // var downloadExcelForm = $('#download-chart-form');
                // downloadExcelForm.submit();

                // $('#download-chart-form').submit();
                DownloadPNG(dataUrl);
            };

            img.src = url;
        }

DownloadPNG向服务器发送一个帖子,C#执行以下操作:

        var base64Data = Regex.Match(dataUrl, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
        var binData = Convert.FromBase64String(base64Data);

        using (var stream = new MemoryStream(binData))
        {
            var tempFolder = ConfigurationManager.AppSettings["tempFilesDirectory"];
            var bitmap = new Bitmap(stream);

            var folder = Server.MapPath(tempFolder);
            var imagePath = folder + $"/{Guid.NewGuid().ToString()}.png";
            bitmap.Save(imagePath);

            //return File(imagePath, "image/png", "Chart.png");
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment;filename=Chart.png");
            Response.WriteFile(imagePath);
            Response.End();
        }
提问于
用户回答回答于

这样试试:

downloadPng=function(){
   var img = new Image();
   img.onload = function (){
	var canvas = document.createElement("canvas");
	canvas.width = img.naturalWidth;
	canvas.height = img.naturalHeight;
	var ctxt = canvas.getContext("2d");
	ctxt.fillStyle = "#fff";
	ctxt.fillRect(0, 0, canvas.width, canvas.height);
        ctxt.drawImage(img, 0, 0);
	var a = document.createElement("a");
	a.href = canvas.toDataURL("image/png");
	a.download = "image.png"
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
   };
   var svgText = document.getElementById("div-surrounding-svg-element").innerHTML;
   img.src = "data:image/svg+xml;utf8," + encodeURIComponent(svgText);
}
<div id="div-surrounding-svg-element">
<svg height="100" width="500" xmlns="http://www.w3.org/2000/svg"><svg height="100" width="500" xmlns="http://www.w3.org/2000/svg">
  <ellipse cx="240" cy="50" rx="220" ry="30" style="fill:green" />
  <ellipse cx="220" cy="50" rx="190" ry="20" style="fill:white" />
</svg>
  <ellipse cx="240" cy="50" rx="220" ry="30" style="fill:yellow" />
  <ellipse cx="220" cy="50" rx="190" ry="20" style="fill:white" />
</svg>
</div>
<button onclick="downloadPng()">download</button>

扫码关注云+社区

领取腾讯云代金券