1、获取本地上传图片的base64编码
var file = $_('upload_file').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
imgBase64 = e.target.result;
};
点击了解FileReader
2、获取图片资源的base64编码
function getBase64Image(img,width,height) {//width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
var canvas = document.createElement("canvas");
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL();
return dataURL;
}
var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg"
var image = new Image();
image.crossOrigin = '';
image.src = img;
var deferred=$.Deferred();
if(img){
image.onload =function (){
deferred.resolve(getBase64Image(image));//将base64传给done上传处理
}
return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
}