js把图片转化成base64

	function getImgToBase64(url,callback){//将图片转换为Base64
	  var canvas = document.createElement('canvas'),
	    ctx = canvas.getContext('2d'),
	    img = new Image;
	  img.crossOrigin = 'Anonymous';
	  img.onload = function(){
	    canvas.height = img.height;
	    canvas.width = img.width;
	    ctx.drawImage(img,0,0);
	    var dataURL = canvas.toDataURL('image/png');
	    callback(dataURL);
	    canvas = null;
	  };
	  img.src = url;
	}

使用方式

getImgToBase64('img/test.png',function(data){
   var myFile = dataURLtoFile(data,'testimgtestimgtestimg');
   console.log(myFile);
});

你可能感兴趣的:(js把图片转化成base64)