Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

url、base64、blob互转 #35

Open
gnipbao opened this issue Jun 17, 2019 · 0 comments
Open

url、base64、blob互转 #35

gnipbao opened this issue Jun 17, 2019 · 0 comments

Comments

@gnipbao
Copy link
Owner

gnipbao commented Jun 17, 2019

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);
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant