美文网首页
JS图片转base64

JS图片转base64

作者: LHQ丶 | 来源:发表于2021-07-09 10:11 被阅读0次
export function image2Base64(file, maxW, maxH) {
  return new Promise(resolve => {
    // 后缀名
    const type = file.name.split('.').pop();
    // 文件路径
    const dataURl = (window.URL || window.webkitURL).createObjectURL(file);
    var img = new Image();
    img.src = dataURl;
    img.onload = function() {
      const canvas = document.createElement('canvas');

      if (img.width > maxW || img.height > maxH) {
        let w = maxW;
        let h = maxW * img.height / img.width;
        if (h > maxH) {
          w = maxH * img.width / img.height;
          h = maxH;
        }
        canvas.width = w;
        canvas.height = h;
      } else {
        canvas.width = img.width;
        canvas.height = img.height;
      }
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      const dataURL = canvas.toDataURL('image/' + type);
      resolve(dataURL);
    };
  });
}

export function image2Base64_2(file) {
  return new Promise(resolve => {
    const type = file.name.split('.').pop();
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e) {
      const url = this.result.substring(this.result.indexOf(',') + 1);
      const imgUrl = `data:image/${type};base64,${url}`
      resolve(imgUrl);
    }
  })
}

function change(ev) {
  const file = ev.target.files[0];
  if (file.size > 2e6) {
    alert('图片大小不能超过2M');
    return;
  }
  image2Base64(file, 300, 200).then(base64 => {
    console.log(base64);
  })
}

相关文章

网友评论

      本文标题:JS图片转base64

      本文链接:https://www.haomeiwen.com/subject/htxfpltx.html