Search code examples
javascriptpdfmake

Base64 encoding an image alerts correct, response is nil


I'm trying to encode an image in Base64 from a URL.

function getBase64Image(url) {
  var img = new Image(),
      response = '';

  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');
    response = dataURL;
    alert(response);
  };

  img.src = url;
  return response;
}

The alert() works fine but the response is nil:

alert

You can see in the console in the screenshot if I log the response like so (it's done twice in the screenshot) it returns nothing:

console.log(getBase64Image('<%= asset_path "test.jpg" %>'));

Obviously we can read the image because the alert has the encoding. What am I missing?

Update

Relevant JSFiddle: https://jsfiddle.net/guxzxq20/3/


Solution

  • Approach: Canvas

    Load the image into an Image-Object, paint it to a non-tainted canvas and convert the canvas back to a dataURL.

    function convertImgToDataURLviaCanvas(url, callback, outputFormat) {
      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(outputFormat);
        callback(dataURL);
        canvas = null;
      };
      img.src = url;
    }
    

    call method

    convertImgToDataURLviaCanvas('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png',function(response){
     alert(response)
    });