总结几个Base64转Blob对象、网络图片转Base64、转Blob(url)的方法

function dataURLtoBlob(dataurl) {// Base64转Blob对象
  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 });
}

function blobToDataURL(blob, callback) { // Blob对象转Base64
    let a = new FileReader();
    a.onload = function (e) { 
      callback(e.target.result); 
    }
    a.readAsDataURL(blob);
}

// 转Blob (url)
function getObjectURL(file) { 
  var url = null;
  if (window.createObjectURL !== undefined) { // basic
      url = window.createObjectURL(file);
  } else if (window.URL !== undefined) { // mozilla(firefox)
      url = window.URL.createObjectURL(file);
  } else if (window.webkitURL !== undefined) { // webkit or chrome
      url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

// Base64转Blob对象
function dataURItoBlob(base64Data) {  
  var byteString;
  if(base64Data.split(',')[0].indexOf('base64') >= 0) {
    byteString = atob(base64Data.split(',')[1]);
  } else {
    byteString = unescape(base64Data.split(',')[1]);
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  }
  var ia = new Uint8Array(byteString.length);
  for(var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], {type: mimeString})
}

// 网络图片转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;
}

export default { dataURLtoBlob, blobToDataURL,getObjectURL, dataURItoBlob, convertImgToBase64 }

你可能感兴趣的:(总结几个Base64转Blob对象、网络图片转Base64、转Blob(url)的方法)