1. 程式人生 > >圖片轉化成base64編碼

圖片轉化成base64編碼

var img = "imgurl";//imgurl 就是你的圖片路徑  

function getBase64Image(img) {  
     var canvas = document.createElement("canvas");  
     canvas.width = img.width;  
     canvas.height = img.height;  
     var ctx = canvas.getContext("2d");  
     ctx.drawImage(img, 0, 0, img.width, img.height);  
     var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();  
     var dataURL = canvas.toDataURL("image/"+ext,0-1);(0-1    表示圖片的質量)  
     return dataURL;  
}  

var image = new Image();  
image.src = img;  
image.onload = function(){  
  var base64 = getBase64Image(image);  
  console.log(base64);  
}