1

I have already made a simple log system where i get the Base64 Code from a text string:

var myString = 'Hello everyone, my name is Dennis';
var b64 = btoa(myString);
var unicode = atob(b64);
console.log(b64);
console.log(unicode);

The output is a Base64 Code like i said, but what i am trying to is to convert an uploaded image to Base64. Here is what i got so far, the output what i get from this is the whole webpage in base64 code. i hope someone could help me out.

function toDataUrl(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.send();
}



//use

var captcha = document.getElementById('logo').src;
toDataUrl(captcha, function(base64Img) {
    log(captcha);
});

Thanks in advance!

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Dennis Offinga
  • 85
  • 1
  • 1
  • 9

1 Answers1

2

There I made you a working example if the duplicate doens't help you: (And be aware of CORS if your image is not heberged on the same domain of the request)

function toDataUrl(src, callback) {
  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.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL();
    callback(dataURL);
  };
  img.src = src;

}

toDataUrl("http://i.imgur.com/rx3kylA.png", function(base64Img) {
  console.log(base64Img);
});
Dipiks
  • 3,818
  • 2
  • 23
  • 39