1

I'm trying to convert a image to a base64 string and put it as source into an img tag. The picture is stored on a other subdomain then the scripts. So i put this in my .htaccess file to ensure, the access is allowed

<ifModule mod_headers.c>
  Header set Access-Control-Allow-Origin http://xxx.mydomain.com
  Header set Access-Control-Allow-Credentials true
</ifModule>

It's working pretty well on Desktop Browsers, Safari on iOS and Chrome on Android. But not in Androids native browser. All i got in the console is

Uncaught Error: SecurityError: DOM Exception 18

Any idea why it's working on all browser but not on the androids one? Here's my script

function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.onload = function(){
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/jpg');
        callback.call(this, dataURL);
        canvas = null;
    };
    img.crossOrigin = 'anonymous';
    img.src = url;
}

var imgString;

if (localStorage.getItem('xxxItemNamexxx')) {
    imgString = localStorage.getItem('xxxItemNamexxx');
} else {
    convertImgToBase64($('#my-picture').attr('src'), function(base64Img) {
        imgString = base64Img;
        localStorage.setItem('xxxItemNamexxx', base64Img);
    });
}

$('#my-picture').attr('src', imgString);

Thanks for any inputs!

schaenk
  • 633
  • 1
  • 6
  • 17

1 Answers1

0

I had similar issue in android and this answer helped.

function convertImgToBase64(url, callback, outputFormat){
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);

  xhr.responseType = 'arraybuffer';

  xhr.onload = function(e) {
    if (xhr.status == 200) {
      var uInt8Array = new Uint8Array(xhr.response);
      var i = uInt8Array.length;
      var binaryString = new Array(i);
      while (i--) {
        binaryString[i] = String.fromCharCode(uInt8Array[i]);
      }
      var data = binaryString.join('');
      var base64 = window.btoa(data);
      var dataUrl = "data:" + (outputFormat || "image/png") + ";base64," + base64;
      callback.call(this, dataUrl);
    }
  };

  xhr.send();
}
Community
  • 1
  • 1
Ikrom
  • 4,785
  • 5
  • 52
  • 76