侧边栏壁纸
博主头像
EinTao博主等级

昨天再好,也走不回去;明天再难,也要抬脚继续。

  • 累计撰写 32 篇文章
  • 累计创建 3 个标签
  • 累计收到 1 条评论
标签搜索

目 录CONTENT

文章目录

blob、file、base64、url互转

EinTao
2022-11-26 / 0 评论 / 0 点赞 / 16 阅读 / 361 字

file or blob 转 base64

function fileOrBlobToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    console.log(reader);
    reader.readAsDataURL(file);
    reader.onload = function () {
      resolve(this.result);
    };
    reader.onerror = function () {
      reject("文件读取失败");
    };
  });
}

base64 转 file or blob

function base64ToFileOrBlob(dataurl, fileName) {
  const arr = dataurl.split(",");
  const mimetype = arr[0].match(/:(.*?);/)[1]; // 文件类型
  const bstr = atob(arr[1]); // 解码base64字符串
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return fileName
    ? new File([u8arr], fileName, { type: mimetype })
    : new Blob([u8arr], { type: mimetype });
}

url 转 base64

function urlToBase64(url, minetype = "image/jpg") {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new Image();
    img.crossOrigin = "Anonymous"; // 同源策略
    img.onload = function () {
      canvas.height = this.naturalHeight; // 图片原始尺寸
      canvas.width = this.naturalWidth;
      ctx.drawImage(img, 0, 0);
      const dataURL = canvas.toDataURL(minetype);
      resolve(dataURL);
      canvas = null;
    };
    img.onerror = function (error) {
      reject(error);
    };
    img.src = url;
  });
}

practise 实践

<input type="file" onchange="change(this)" />
<img id="avatar" src="" alt="" />
<img id="avatar1" src="" alt="" />
<img id="avatar2" src="" alt="" />
<img id="avatar3" src="" alt="" />
function change(target) {
  const file = target.files[0];
  // file => base64
  fileOrBlobToBase64(file).then((res) => {
    document.querySelector("#avatar").setAttribute("src", res); // base64

    console.log(base64ToFileOrBlob(res, "头像"));

    // base64 => blob
    const blob = base64ToFileOrBlob(res);
    document
      .querySelector("#avatar1")
      .setAttribute("src", window.URL.createObjectURL(blob));

    // blob => base64
    fileOrBlobToBase64(blob).then((dataurl) => {
      document.querySelector("#avatar2").setAttribute("src", dataurl); // base64
    });
  });
}

window.onload = function load(params) {
  urlToBase64("http://localhost:3000/images/avatar/picture.jpg").then((res) => {
    document.querySelector("#avatar3").setAttribute("src", res); // base64
  });
};
0

评论区