美文网首页
图片压缩

图片压缩

作者: 萤火kin | 来源:发表于2022-05-15 15:11 被阅读0次

    参考:https://www.jianshu.com/p/d05f684b715d

    • 不需要下载插件,用封装的Canvas方法压缩

    • utils文件:

    /**
     * 图片压缩工具类
     * 最大高度和最大宽度都为 500,如果超出大小将等比例缩放。
     *
     * 注意可能出现压缩后比原图更大的情况,在调用的地方自己判断大小并决定上传压缩前或压缩后的图到服务器。
     */
    
    // 将base64转换为blob
    export function convertBase64UrlToBlob(urlData) {
      let arr = urlData.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    }
    
    // 压缩图片
    export function compressImage(path) {
      //最大高度
      const maxHeight = 500;
      //最大宽度
      const maxWidth = 500;
    
      return new Promise((resolve, reject) => {
        let img = new Image();
        img.src = path;
        img.onload = function() {
          const originHeight = img.height;
          const originWidth = img.width;
          let compressedWidth = img.height;
          let compressedHeight = img.width;
          if (originWidth > maxWidth && originHeight > maxHeight) {
            // 更宽更高,
            if (originHeight / originWidth > maxHeight / maxWidth) {
              // 更加严重的高窄型,确定最大高,压缩宽度
              compressedHeight = maxHeight;
              compressedWidth = maxHeight * (originWidth / originHeight);
            } else {
              //更加严重的矮宽型, 确定最大宽,压缩高度
              compressedWidth = maxWidth;
              compressedHeight = maxWidth * (originHeight / originWidth);
            }
          } else if (originWidth > maxWidth && originHeight <= maxHeight) {
            // 更宽,但比较矮,以maxWidth作为基准
            compressedWidth = maxWidth;
            compressedHeight = maxWidth * (originHeight / originWidth);
          } else if (originWidth <= maxWidth && originHeight > maxHeight) {
            // 比较窄,但很高,取maxHight为基准
            compressedHeight = maxHeight;
            compressedWidth = maxHeight * (originWidth / originHeight);
          } else {
            // 符合宽高限制,不做压缩
          }
          // 生成canvas
          let canvas = document.createElement("canvas");
          let context = canvas.getContext("2d");
          canvas.height = compressedHeight;
          canvas.width = compressedWidth;
          context.clearRect(0, 0, compressedWidth, compressedHeight);
          context.drawImage(img, 0, 0, compressedWidth, compressedHeight);
          let base64 = canvas.toDataURL("image/*", 0.8);
          let blob = convertBase64UrlToBlob(base64);
          // 回调函数返回blob的值。也可根据自己的需求返回base64的值
          resolve(blob);
        };
      });
    }
    
    
    • 在项目中使用
    <van-field name="clinicalUrl" label="临床实践记录上传">
      <template #input>
        <van-uploader image-fit="contain" @delete="deleteFile" :accept="'image/*'" :after-read="afterRead" :max-count="3" v-model="uploader" />
      </template>
    </van-field>
    
    import {compressImage} from '../utils/CompressImageUtils'
    
    deleteFile() {
      // this.data.clinicalUrl = '';
      // this.picAfterRead = false
      console.log('我点击了删除')
    },
    
    afterRead(file) {
      console.log('我点击了图片上传')
      this.picAfterRead = false
      file.status = 'uploading'
      file.message = '上传中...'
      compressImage(file.content).then(result => {
        // console.log('压缩后的结果', result); // result即为压缩后的结果
        // console.log('压缩前大小', file.file.size);
        // console.log('压缩后大小', result.size);
        if (result.size > file.file.size){
          console.log('上传原图');
          //压缩后比原来更大,则将原图上传
          this._uploadFile(file.file,file.file.name,file);
        } else {
          //压缩后比原来小,上传压缩后的
          console.log('上传压缩图');
          this._uploadFile(result,file.file.name,file)
        }
      })
    },
    _uploadFile(result,filename, file){
      let params = new FormData()
      params.append('file', result,filename)
      this.axios.post('/app/ossUpload', params).then(res => {
        const { code, msg } = res || {};
        if (code === 0) {
          // this.data.clinicalUrl = msg;
          file.url = msg
          this.picAfterRead = true
          file.status = 'done'
          file.message = ''
        } else {
          this.Toast(msg)
          this.picAfterRead = true
          file.status = 'failed'
          file.message = '上传失败'
        }
      })
    },
    
    onSubmit() {
      if (this.uploader.length !== 0 && this.picAfterRead) {
        this.isDisabled = true
        const { departmentCode, startTimeText, endTimeText } = this.data;
        if (new Date(endTimeText).getTime() - new Date(startTimeText).getTime() < 0) {
          this.Toast('结束时间不能小于开始时间')
          this.isDisabled = false
          return;
        }
        this.data.clinicalUrl = this.uploader.map((item) => item.url).join(')(');
        this.axios.post('/app/addClinicalRecord', this.data).then(res => {
          const { code, msg } = res || {};
          if (code === 0) {
            this.Toast(msg)
            this.$router.push({ path: '/home', query: { index: 'b' } })
            this.isDisabled = false
          } else {
            this.Toast(msg)
            this.isDisabled = false
          }
        })
      } else if (!this.picAfterRead && this.uploader.length !== 0) {
        this.Toast('图片上传中,稍后点击')
      } else {
        this.Toast('需上传临床实践记录')
      }
    },
    },
    

    相关文章

      网友评论

          本文标题:图片压缩

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