将图片转为base64

原理:canvas.toDataURL

<template>
  <div id="app">
    <div class="ocr_img" >
      <input
        style="display: block;"
        type="file"
        accept="image/*"
        capture="camera"
        @change="getOcrImage($event)"
      />
      <img :src="imgUrl" />
      <div>base64编码为:</div>
      <div style="word-wrap: break-word;">{{pic}}</div>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: 'App',
  data(){
    return {
      imgUrl:'',
      pic:'',
    }
  },
  methods:{
    getOcrImage(e) {
      let that = this;
      // 重新上传时清空原数据
      that.base64img = "";
      that.pic = "";
      if (e.target.files.length) {//判断照片是否上传成功
        let file = e.target.files[0];//拿到上传文件的属性对象
        let reader = new FileReader();
        reader.readAsDataURL(file);//调用FileReader对象的readAsDataURL方法,将文件读取为DataURL
        let fileSize = Math.round(e.target.files[0].size / 1024 / 1024);
        reader.onload = function() {
          img.src = this.result;
          that.showNext = true;
        };
        let img = new Image(),
          maxW = 1000,
          canvas = document.createElement("canvas"),
          drawer = canvas.getContext("2d");
      img.crossOrigin = 'Anonymous';//设置跨域
        img.onload = function() {
          if (img.width > maxW) {//图片压缩
            img.height *= maxW / img.width;
            img.width = maxW;
          }
          canvas.width = img.width;
          canvas.height = img.height;
          drawer.clearRect(0, 0, canvas.width, canvas.height);
          drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
          let compressRate = that.getCompressRate(1, fileSize);//图片压缩
          let base64 = canvas.toDataURL("image/jpeg", compressRate); // 这里就拿到了压缩后的base64图片
          let pic = base64.split(",")[1];
          that.base64img = pic;
          that.pic = pic;
          that.imgUrl = "data:image/png;base64," + pic;
          // 清空文件上传控件的值  不清理会出现选择同样的图片会无法触发input事件了
          e.target.value = null;
        };
      }
    },
    getCompressRate(allowMaxSize, fileSize) {
      let compressRate = 1;
      if (fileSize / allowMaxSize > 4) {
        compressRate = 0.6;
      } else if (fileSize / allowMaxSize > 3) {
        compressRate = 0.7;
      } else if (fileSize / allowMaxSize > 2) {
        compressRate = 0.8;
      } else if (fileSize / allowMaxSize > 1) {
        compressRate = 0.9;
      } else {
        compressRate = 1;
      }
      return compressRate;
    }
  }
}
/* eslint-disable */
</script>

结果截图:

 

 

posted @ 2020-11-23 16:06  早起开拓者  阅读(235)  评论(0编辑  收藏  举报