前端 js中图片地址转base64(简单好用)

直接复制走,把想转的图片地址放进去就行 !

function getBase64(imgUrl) {
    window.URL = window.URL || window.webkitURL;
    var xhr = new XMLHttpRequest();
    xhr.open("get", imgUrl, true);
    xhr.responseType = "blob";
    xhr.onload = function(){
        if(this.status == 200){
            //得到一个blob对象
            var blob = this.response;
            console.log("blob", blob)
            // 至关重要
            let oFileReader = new FileReader();
            oFileReader.onloadend = function(e){
                // 此处拿到的已经是base64的图片了,可以赋值做相应的处理
                console.log(e.target.result)
            }
            oFileReader.readAsDataURL(blob);
        }
    }
    xhr.send();
}

getBase64('需要转成base64的图片url')


版权声明:本文为weixin_61175223原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。