Taro上传图片及压缩实操

由于业务要求上传证书的功能,即上传图片,做一下笔记;

tool是我自己封装的微信小程序接口,具体实现看微信小程序或Taro官方文档;req开头的函数也是我自己封装的网络请求;不能够直接复制运行。

界面需要三个东西 上传图片的按钮,选择的按钮,以及上传图片后的图片展示。

 //选择图片的按钮
<Image src={btn} mode='widthFix' className='phone-btn' onClick={this.chooseImage} /> 
//图片展示
<Image src={ this.state.tempFilePaths} style={{width:'100%'}} mode='widthFix'/>
//确认上传图片的按钮
<Button onClick={this.uploadFile}>确认上传证书</Button>  

选择图片函数chooseImage

chooseImage = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original','compressed'],
      sourceType: ['album','camera'],
      success: (res) => {
        tool.showInfo('正在上传...','loading')
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;
        this.setState({
          tempFilePaths: tempFilePaths[0],
        },()=>{
          console.log(tempFilePaths);
        })

      }
    })
  }

上传图片函数uploadFile

 uploadFile=async ()=>{
    let res = await reqUploadCert (this.state.tempFilePaths, 'triCertificate')
    console.log('uploadFile',res)
    let response = JSON.parse(res.data)
    console.log(response);
    if(response.code === 10000){
      console.log('上传成功')
      tool.showInfo('上传成功')
      setTimeout(()=>{
        this.setState({
          showUpload :false,
          tempFilePaths:''
        },()=>{
          this.getCertList()
        })
      },100)
    }else{
      tool.showInfo('上传失败')
    }
  }

当图片上传成功后,我们需要展示在页面上,没上传图片之前,需要留白高度400rpx的View,好看些。

{
   this.state.tempFilePaths ?<Image src={ this.state.tempFilePaths} style={{width:'100%'}} mode='widthFix'/>
   : <View style={{width:'100%',height:'400rpx'}}></View>
}

业务中另外的上传图片功能需要压缩图片,这一块我做了很久,(现在还是不会图片的裁剪,会做时补充上来)

//压缩图片
 chooseWxImage = () => {
     //选择图片
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log('选择图片=>', res.tempFilePaths[0])
        Taro.getImageInfo({
          src: res.tempFilePaths[0],
          success: (res) => {
            console.log('getImageInfo=>res', res)
            console.log('getImageInfo=>', res.path)
            let originW = res.width
            let originH = res.height
            //压缩比例
            //最大尺寸限制,这里我不知道为什么规定的320和420无法压缩到对应的值,只好/3试试,发现可以
            let maxW = 320 /3
            let maxH = 420 /3
            //目标尺寸
            let targetW = originW
            let targetH = originH
            if (originW > maxW || originH > maxH) {
              if (originW / originH > maxW / maxH) {
                // 要求宽度*(原生图片比例)=新图片尺寸
                targetW = maxW;
                targetH = Math.round(maxW * (originH / originW));
              } else {
                targetH = maxH;
                targetW = Math.round(maxH * (originW / originH));
              }
            }
            //尝试压缩文件,创建 canvas
            let ctx = Taro.createCanvasContext('firstCanvas');
            ctx.clearRect(0,  0, targetW, targetH);
            console.log(res.path, targetW, targetH)
            ctx.drawImage(res.path, 0, 0, targetW  , targetH );
            ctx.draw();
            //设置canvas的长宽
            this.setState({
              cw: targetW  ,
              ch: targetH
            })
            setTimeout(()=>{
              Taro.canvasToTempFilePath({
                canvasId: 'firstCanvas',
                width:targetW ,
                height : targetH  ,
                success: (res) => {
                  console.log('画布信息=>', res)
                  console.log('画布信息=>', res.tempFilePath)
                  Taro.getImageInfo({
                    src : res.tempFilePath ,
                    success : (res)=>{
                      console.log('压缩后的res',res)
                    }
                  })
                  this.setState({
                    tempFilePaths: res.tempFilePath,
                    hidden: true,
                    isChanged: true
                  })
                  Taro.setStorageSync('userImage',res.tempFilePath)
                }
              })
            },500)
          }
        })
      }
    })
  }

使用Canvas才能得到压缩后的图片

 const style = {height: this.state.ch + 'px', width: this.state.cw + 'px', marginLeft: -this.state.cw / 2 + 'px'}
 
<View style={style} className='hiddenCanvas'>
      <Canvas className='canvas' canvasId="firstCanvas" style={style} />
</View>
.canvas{
  position: absolute;
  top: 0;
  left:50%;
  z-index: -1;
}
.hiddenCanvas{
  position: fixed;
  top: 9999rpx;  //把canvas移出屏幕
}

显示部分与上传图片类似,不赘述,当有底图的情况下,不用留白一个View的位置,直接使用底图即可。

state={
    ...
    tempFilePaths: require('../../../images/apply/background.png'),
} 

<View>
    <Image src={this.state.tempFilePaths} style='width: 100%;' mode='widthFix' className='phone-bgc'/>
</View>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容