远程图片转成base64,网上一搜,基本都是说用canvas的toDataURL()来实现,实际上这会遇到跨域安全限制。目前,唯一可行的方案是,把图片文件以arraybuffer的形式ajax下载下来,然后直接转base4。但是,这样有个毛病,就是可能会浪费带宽,多下载一次。
var getBase64ByUrl = function(src, callback, outputFormat) {
var xhr = new XMLHttpRequest();
xhr.open('GET', src, 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;
alert(dataUrl)
callback.call(this, dataUrl);
}
};
xhr.send();
}
原文:https://www.cnblogs.com/youryida/p/4914503.html
参考:http://stackoverflow.com/questions/22783368/android-browser-only-canvas-todataurl-throws-uncaught-error-securityerror-dom