Canvas element can be used to draw SVG images and its toDataURLfunction can be used to convert SVG to data URL string (Base64). This article shows you how to convert SVG to Base64 string and also the other way around.
Convert SVG to Base64
The following function converts compatible images including SVG to Base64 data URL.
/** * Convert image to data URL * @param {any} url */function getDataURL(url) { return new Promise((resolve, reject) => { var img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function () { var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var dataURL; canvas.height = this.naturalHeight; canvas.width = this.naturalWidth; ctx.drawImage(this, 0, 0); dataURL = canvas.toDataURL(); resolve(dataURL); };
img.onerror = function () { resolve(url); };
img.src = url; if (img.complete || img.complete === undefined) { img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; img.src = url; } });}
It involves the following:
- Create an Imageobject.
- In image onload event, create a Canvaselement.
- Use the canvas object to draw image.
- And then use canvas toDataURLfunction to convert the image to Base64 string.
- Set the Image object URL as the input URL.
- Once image is loaded, return the Base64.
- The whole function returns a Promiseobject as the image will take time to load.
Use this function
We can then use this function to convert SVG URL to Base64.
getDataURL('https://app.kontext.tech/api/flex/diagram/diagram-903').then(base64=>{alert(base64);});
SVG XML to Base64 string
If the input is not a SVG URL but a SVG XML string, we can then use the following code:
/** * Convert SVG xml to png base64 url * @param {any} svgXml */function getImageDataURL(svgXml) { return "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgXml)));}
JavaScript btoafunction is used to convert XML string to Base64 string.
If you have to return it as a Promise, try the following function:
/** * Convert SVG xml to png base64 url * @param {any} svgXml */function getImageDataURL(svgXml) { return new Promise((resolve, reject) => { var img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function () { var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var dataURL; canvas.height = this.naturalHeight; canvas.width = this.naturalWidth; ctx.drawImage(this, 0, 0); dataURL = canvas.toDataURL("image/png", 1); resolve(dataURL); };
img.onerror = function () { resolve(url); };
img.src = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgXml))); if (img.complete || img.complete === undefined) { img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; img.src = url; } });}
Convert Base64 string to HTML File object
The following function coverts a Base64 string to a HTML form Fileobject.
/** * Convert data URL to file * @param {any} dataurl * @param {any} filename */function dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, { type: mime });}
Summary
The above code works for SVG and also other image formats.