js 圖片與base64互相轉換

js將圖片轉化爲base64html

參考地址:http://www.cnblogs.com/mr-wuxiansheng/p/6931077.htmlcanvas

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);  
     return dataURL;  
}  

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

js將base64轉化爲圖片格式segmentfault

參考地址:https://segmentfault.com/q/1010000010236626url

js直接設置img的src屬性爲 圖片的base64數據便可spa

document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0 DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' );code

相關文章
相關標籤/搜索