0

I am trying to convert an image url to a base64 image. I have found this which I am trying to make use of.

I have the following code:

var imgUrl = 'https://www.google.de/images/srpr/logo11w.png';
let base64image = this.getBase64Image(imgUrl);
console.log(base64image);

and

public getBase64Image(imgUrl) {
    var img = new Image();
    img.src = imgUrl;
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

But, it outputs the following:

data:,

I get the following error in the console:

EXCEPTION: Uncaught (in promise): SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. Error: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

My code must me incoreect. Can anyone please advise how to convert the url to a base64 image?

Thanks

UPDATE

I aded the following line to the function:

img.crossOrigin = "Anonymous";

That got rid of the error, however, now I get the following:

data:,

Community
  • 1
  • 1
Richard
  • 8,193
  • 28
  • 107
  • 228

1 Answers1

0

You can use an XHR and the File Reader API instead, which is cleaner but is limited in browser compatibility.

var imgxhr = new XMLHttpRequest();
    imgxhr.open( "GET", url );
    imgxhr.responseType = "blob";
    imgxhr.onload = function (){
        if ( imgxhr.status===200 ){
            reader.readAsDataURL(imgxhr.response);
        }
        else if ( imgxhr.status===404 ){
            // Error handle
        }
    };
var reader = new FileReader();
    reader.onloadend = function () {
        console.log(reader.result.length);
        // Code here
    };
imgxhr.send();
Jason
  • 779
  • 1
  • 9
  • 30