简体   繁体   English

将svg转换为带有图像标签的png以获得Base64

[英]Transform svg to png with image tag inside to get Base64 on it

I'm having trouble of generating my SVG to PNG using <image> in order of getting Base64, my fiddle example shows that is not possible. 我在使用<image>生成SVG到PNG以获取Base64的顺序时遇到了麻烦,我的小提琴示例显示这是不可能的。 Is there any workaround for this? 有什么解决方法吗?

Or is it possible to transform this data = "data:image/svg+xml;base64," + btoa(xml) into image/png;base64 ? 还是可以将data = "data:image/svg+xml;base64," + btoa(xml)转换为image/png;base64 Based on this fiddle example 基于这个小提琴的例子

The xlink:href attribute appear to be cross-origin , which would result in error xlink:href属性似乎是跨源的,这将导致错误

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement':
Tainted canvases may not be exported.

being returned when canvas.toDataURL() called http://jsfiddle.net/meertskm/5/ canvas.toDataURL()调用http://jsfiddle.net/meertskm/5/时返回


Updated 更新

Try utilizing XMLHttpRequest see Sending and Receiving Binary Data 尝试利用XMLHttpRequest参见发送和接收二进制数据

Also you can read a binary file as a Blob by setting the string "blob" to the responseType property. 通过将字符串“ blob”设置为responseType属性,您还可以将二进制文件读取为Blob。

  // create `img` element var img = new Image; img.width = 100; img.height = 100; // log when complete img.onload = function () { // see `src` at `this` console.log(this.complete, this); }; // set `url` of `request` with `svg` `image` `xlink:href` var link = document.querySelectorAll("svg")[0] .children[0].attributes .getNamedItem("xlink:href").value; var request = new XMLHttpRequest(); request.responseType = "blob"; request.open("GET", link, true); request.onload = function (e) { var blob = this.response; var reader = new FileReader(); reader.onload = function (e) { // `data URI` of request image console.log(e.target.result); // set `img` `src` to `e.target.result`:`data URI` img.src = e.target.result; // append `img` next to `svg` document.body.appendChild(img); }; reader.readAsDataURL(blob); }; // log error request.onerror = function(e) { console.log(e); }; request.send(); 
 <svg height="100" width="100" id="asd" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <image id="testimg1" xlink:href="http://i.imgur.com/LQIsf.jpg" width="100" height="100" x="0" y="0" /> </svg> 

jsfiddle http://jsfiddle.net/meertskm/4/ jsfiddle http://jsfiddle.net/meertskm/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM