JavaScript Convert SVG to Base64

Raymond Raymond event 2021-12-25 visibility 13,011
more_vert

Canvas element can be used to draw SVG images and its toDataURL function 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 Image object.
  • In image onload event, create a Canvas element.
  • Use the canvas object to draw image.
  • And then use canvas toDataURL function 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 Promise object 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://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 btoa function 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 File object.

/**
 * 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. 

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts