js绝对地址图片转换成base64的方法

时间:2022-06-16 07:24:11
//将图片转换成base64
function getBase64Image(url, callback){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image();
//为了解决跨域,可以直接img.crossOrigin=''就能解决图片跨域问题
img.crossOrigin = 'xes';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL('image/png');
callback.call(this, dataURL);
canvas = null;
}
img.src = url;
}
getBase64Image('http://app1.xesimg.com/roommsg/9071347a804c1b2f9b27ee4198f4e738_small.jpg', function(base64Img){
console.log(base64Img)
});