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); //在canvas中画图
var dataURL = canvas.toDataURL(“image/png”); //可选其他值 image/jpeg
return dataURL;
}

    function main(src, cb) {
        var image = new Image();
        image.src = src + '?v=' + Math.random(); // 处理缓存
        image.crossOrigin = "*";                 // 支持跨域图片
        image.onload = function() {
            var base64 = getBase64Image(image);
            cb && cb(base64);
        }
    }

    main('https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2581919349,4180465790&fm=26&gp=0.jpg', function(base64) {
        console.log(base64);
    });

你可能感兴趣的:(在线资源转成base64)