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});
}javascript

 

 

//能夠將圖片轉換爲base64java

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

相關文章
相關標籤/搜索