js 图片转换base64 base64转换为file对象

js 图片转换base64 base64转换为file对象

 

function getImgToBase64(url,callback){//将图片转换为Base64
  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('image/png');
    callback(dataURL);
    canvas = null;
  };
  img.src = url;
}

 

 

    function dataURLtoFile(dataurl, filename) {//将base64转换为文件
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    }

 

//可以将图片转换为base64

getImgToBase64('img/test.png',function(data){
   var myFile = dataURLtoFile(data,'testimgtestimgtestimg');
   console.log(myFile);
});

 

 

相关: https://www.cnblogs.com/fps2tao/p/9268380.html

 

posted @ 2018-07-05 15:35  与f  阅读(25163)  评论(0编辑  收藏  举报