canvas压缩二进制图片

``

react项目

dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
      }
      // 图片压缩
       getsmallpic(file){
        return new Promise((resolve,reject)=>{
            //对图片进行压缩
            const reader = new FileReader()
            const image = new Image()
            image.onload = (imageEvent) => {
              const canvas = document.createElement('canvas');
              const context = canvas.getContext('2d'); //画布上绘制的类型为2D
              const width = image.width * 0.5
              const height = image.height * 0.5
              canvas.width = width;
              canvas.height = height;
              context.clearRect(0, 0, width, height);// 清空给定矩形内的指定像素。
              context.drawImage(image, 0, 0, width, height); //在画布上定位图像,并规定图像的宽度和高度
              const dataUrl = canvas.toDataURL(file.type);
              const blobData = this.dataURLtoFile(dataUrl,file.name);
              if(blobData){
                if(blobData.size /1024 < 400){
                  Object.assign(blobData,{uid:blobData.lastModified});
                    const windowURL = window.URL || window.webkitURL;//实现预览
                  resolve(blobData)
                  this.setState({
                    imgSrc:windowURL.createObjectURL(blobData),
                    class:1
                   }) 
                   this.setState({
                    imgArr:blobData
                })
                }else{
                  this.getsmallpic(blobData)
                }
                
              }else{
                reject()
              }
              
            }
            reader.onload = (e => { image.src = e.target.result; });
            reader.readAsDataURL(file);
        })
      }
```humanChange(e){               //文件上传事件
         const windowURL = window.URL || window.webkitURL;//实现预览
        const file = document.getElementById('faceHuman').files[0];
        console.log(file.size/1024+'kb')
        const isLt400K = file.size /1024 < 400;
        if(!isLt400K){
          // let newfile =await getsmallpic(file)
          return this.getsmallpic(file)
        }else{
          this.setState({
            imgSrc:windowURL.createObjectURL(file),
            class:1
           }) 
           this.setState({
            imgArr:file
        })
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值