image, blob, File, base64互相转换方法

//将image url、blob url等转化为blob对象
async function urlToBlob (url) {
  return new Promise((resolve,reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if(this.status == 200 || this.status === 0){
        // 注意这里的this.response 是一个blob对象 就是文件对象
        resolve(this.response)
      }
      else{
        reject(null)
      }
    }
    xhr.send();
  })
}

//将base64转换为blob
function base64toBlob(dataurl) { 
  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 Blob([u8arr], { type: mime });
}

//将blob转换为file
function blobToFile(theBlob, fileName){
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
}

//file转base64
async function fileToBase64(file){
  return new Promise((resolve,reject) => {
    let reader=new FileReader();
    reader.readAsDataURL(file);
    reader.onload=function(e){
      resolve(this.result);
    }
    reader.error=function(){
      reject(this.error);
    }
  })
}

//image转base64
function imgToBase64(img,mime="image/png"){
  let canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  let ctx = canvas.getContext("2d");
  img.crossOrigin= 'anonymous';
  ctx.drawImage(img, 0, 0, img.width, img.height);
  delete img.crossOrigin;
  let dataURL = canvas.toDataURL(mime);
  return dataURL
}

 

posted @ 2021-06-04 16:55  全玉  阅读(1918)  评论(0编辑  收藏  举报