How to get Base64 image from an URL or Image tag

You might need to convert a png/jpeg image to a base64 encoding. The following function does that for you.

function getBase64FromImageUrl(url) {
    var img = new Image();

    img.setAttribute('crossOrigin', 'anonymous');

    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width =this.width;
        canvas.height =this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        var url= dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    };

    img.src = url;
}

Call it like this : getBase64FromImageUrl("images/slbltxt.png").

Otherwise if you have a image in img tag then you may use this function to get the base64 image.

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Here’s how the above function can be used.

var userImage = document.getElementById('userImg');
var imgData= getBase64Image(userImage);

This content has been helpful to you?

Thanks for contributing!

Yes No