Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert inline SVG to Base64 string

Tags:

javascript

svg

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?

like image 314
Niko Lang Avatar asked Feb 11 '15 09:02

Niko Lang


People also ask

Can we convert SVG to Base64?

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.

What is base 64 format?

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.


2 Answers

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.

like image 94
Robert Longson Avatar answered Oct 07 '22 17:10

Robert Longson


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); 
like image 24
Anh Hoang Avatar answered Oct 07 '22 17:10

Anh Hoang