js 图片与base64互相转换

js将图片转化为base64

参考地址:http://www.cnblogs.com/mr-wuxiansheng/p/6931077.html

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转化为图片格式

参考地址:https://segmentfault.com/q/1010000010236626

js直接设置img的src属性为 图片的base64数据即可

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

posted @ 2017-09-15 22:03  lin_zone  阅读(62276)  评论(5编辑  收藏  举报