js 图片转为base64

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 = './images/index/logout.png';  
        image.onload = function(){  
          var base64 = getBase64Image(image);  
          console.log(base64);  
        } 

 

posted @ 2021-10-19 10:09  骅骝漫轻舞01  阅读(369)  评论(0编辑  收藏  举报