前端JS base64与图片互转

然后我就反应过来了,img标签不是可以直接识别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); 

     return dataURL; 

var image = new Image(); 

image.src = img; 

image.onload = function(){ 

  var base64 = getBase64Image(image); 

  console.log(base64); 

在后台getBase64Image()转base64的话会快点

var m = 'data:image/png;base64,' + res.message;                      document.getElementById('qrcode').setAttribute('src', m);

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


如下:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0 DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">

你可能感兴趣的:(html,html5,javascript)