JS图片转换Base64代码

var imgSrc = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";

//传入图片路径,返回base64
function getBase64(img){
	
	function getBase64Image (img,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 image = new Image();
		// 此属性为解决跨域问题
		image.crossOrigin = '';
		image.src = img;
		var deferred = $.Deferred();
		if (img) {
			image.onload = function () {
				// 将base64传给done上传处理
				deferred.resolve(getBase64Image(image));
			}
			return deferred.promise();
		}
		
	}
	
	getBase64(imgSrc).then(function(base64){
		console.log(base64);
	},function(err){
		console.log(err);
	});

注:默认图片存放于阿里云CDN节点,本地及其他图片路径待测试。