vue上传图片base64格式压缩

vue上传图片base64格式压缩_第1张图片
image.png

一个上传头像的功能,后端给的接口可以接收base64格式的,用的UI框架是vant-ui,需求和准备大概就这样,如果对vant-ui不熟的可能需要先去看看vant-ui的上传组件使用方法。

下面展示代码


                
// userImg是压缩后的头像,defaultImg是默认头像
更换头像
  data() {
    return {
      userImg:'',
      defalutImg: require("@/assets/img/default_img.png"),
    };
  },
    // 上传头像,这个方法是vant-ui上传组件的
    async onRead(file) {
      let that = this
      that.userImg = file.content
      that.getImgFun(file.content)
    },
//拿到原始文件的base64的格式
    getImgFun (originalImg) {
      let that = this
      let base64Arr = originalImg.split(",");
      let imgtype = "";
      let base64String = "";
      if (base64Arr.length > 1) {
        //如果是图片base64,去掉头信息
        base64String = base64Arr[1];
        imgtype = base64Arr[0].substring(
          base64Arr[0].indexOf(":") + 1,
          base64Arr[0].indexOf(";")
        );
      }
      // 将base64解码
      let bytes = atob(base64String);
      //let bytes = base64;
      let bytesCode = new ArrayBuffer(bytes.length);
      // 转换为类型化数组
      let byteArray = new Uint8Array(bytesCode);
      // 将base64转换为ascii码
      for (let i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i);
      }
      // 生成Blob对象(文件对象)
      let bolbObj = new Blob([bytesCode], { type: imgtype });
      let reader = new FileReader(); // 这个方法读取文件的bolb对象
      //将图片转成base64格式
      reader.readAsDataURL(bolbObj);
      reader.onloadend = function() {
        let result = this.result;
        let img = new Image();
        img.src = result;
        console.log("********未压缩前的图片大小********");
        console.log(result.length / 1024);
        img.onload = function() {
          let data = that.compress(img, 0.1);
          that.uploadImg(data);
        };
      };
    },
// 压缩图片
    compress(img, size) {
        // 创建canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let initSize = img.src.length
        let width = img.width
        let height = img.height
        canvas.width = width
        canvas.height = height
        // 铺底色
        ctx.fillStyle = '#fff'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(img, 0, 0, width, height)
        //进行最小压缩
        let ndata = canvas.toDataURL('image/jpeg', size)
        console.log('*******压缩后的图片大小*******')
        console.log(ndata.length / 1024)
        return ndata
      },
async uploadImg(base64) {
        console.log(base64)
        this.userImg = base64
      这里可以打印出最终压缩后的base64
        },

你可能感兴趣的:(vue上传图片base64格式压缩)