url、base64、blob互转

@gnipbao 2019-06-17 11:10:23发表于 gnipbao/iblog javascript

url =>base64

let urlToBase64 = url =>
  new Promise((resolve, reject) => {
    let image = new Image();
    image.onload = function() {
      let canvas = document.createElement("canvas");
      canvas.width = this.naturalWidth;
      canvas.height = this.naturalHeight;
      canvas.getContext("2d").drawImage(image, 0, 0);
      let ret = canvas.toDataURL("image/png");
      resolve(ret);
    };
    image.setAttribute("crossOrigin", "Anonymous");
    image.src = url;
    image.onerror = e => {
      reject(e);
    };
  });

base64 => blob

let base2Blob = ({ b64data = "", contentType = "", sliceSize = 512 } = {},filename) =>
  new Promise((resolve, reject) => {
    let byteChars = atob(b64data);
    let byteArrays = [];
    for (let offset = 0; offset < byteChars.length; offset += sliceSize) {
      let slice = byteChars.slice(offset, offset + sliceSize);
      let byteNumbers = [];
      for (let i = 0; i < slice.length; i++) {
        byteNumbers.push(slice.charCodeAt(i));
      }
      byteArrays.push(new Uint8Array(byteNumbers));
    }
    let ret = new Blob(byteArrays, { type: contentType });
    ret = Object.assign(ret, {
        preview : URL.createObjectURL(ret);
        name: `${filename}.png`
    })
  });

blob =>base64

let blob2Base64 = (blob) => new Promise((resolve, reject) => {
  const fileReader = new FileReader();
  fileReader.onload = (e) => {
    resolve(e.target.result);
  }
  fileReader.readAsDataURL(blob);
  fileReader.onerror = (e) => {
    reject(e);
  }
});