通过js将图片url转base64

思路如下:

  1. 构造一个img元素,将url赋给img2. 给元素的内容赋值为你所想要copy的文本
  2. 等待图片加载完成
  3. 构造一个canvas元素
  4. 将img元素画到canvas上
  5. 通过canvas的api将url转化为base64
function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback.call(this, dataURL);
        canvas = null; 
    };
    img.src = url;
}

var url = "static/img/js1.jpg";//这是站内的一张图片资源,采用的相对路径
convertImgToBase64(url, function(base64Img){
    //转化后的base64
    alert(base64Img);
});

你可能感兴趣的:(通过js将图片url转base64)