I want to send an inline SVG image to a PHP script to Convert it to PNG with Imagick. For that I have to know how to get a base64 String out on an inline SVG. For canvas objects its a simple ".toDataURL()" but that doesn't work with inline SVGs, because its not a global function of elements.
test = function(){ var b64 = document.getElementById("svg").toDataURL(); alert(b64); }
http://jsfiddle.net/nikolang/ccx195qj/1/
But how to do it for inline SVGs?
How to convert SVG image to Base64 String? Open SVG to Base64 tool, use Upload SVG button to upload SVG file. Once file is been uploaded, this tool starts converting svg data to base64 and generates Base64 String, HTML Image Code and CSS background Source. Download the converted Base64 data.
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.
Use XMLSerializer to convert the DOM to a string
var s = new XMLSerializer().serializeToString(document.getElementById("svg"))
and then btoa can convert that to base64
var encodedData = window.btoa(s);
Just prepend the data URL intro i.e. data:image/svg+xml;base64,
and there you have it.
I just try to collect and explain all great ideas on this issue. This works on both Chrome 76 and Firefox 68
var svgElement = document.getElementById('svgId'); // Create your own image var img = document.createElement('img'); // Serialize the svg to string var svgString = new XMLSerializer().serializeToString(svgElement); // Remove any characters outside the Latin1 range var decoded = unescape(encodeURIComponent(svgString)); // Now we can use btoa to convert the svg to base64 var base64 = btoa(decoded); var imgSource = `data:image/svg+xml;base64,${base64}`; img.setAttribute('src', imgSource);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With