Taro上傳圖片及壓縮實(shí)操

由于業(yè)務(wù)要求上傳證書的功能,即上傳圖片,做一下筆記;

tool是我自己封裝的微信小程序接口,具體實(shí)現(xiàn)看微信小程序或Taro官方文檔;req開頭的函數(shù)也是我自己封裝的網(wǎng)絡(luò)請(qǐng)求;不能夠直接復(fù)制運(yùn)行。

界面需要三個(gè)東西 上傳圖片的按鈕,選擇的按鈕,以及上傳圖片后的圖片展示。

 //選擇圖片的按鈕
<Image src={btn} mode='widthFix' className='phone-btn' onClick={this.chooseImage} /> 
//圖片展示
<Image src={ this.state.tempFilePaths} style={{width:'100%'}} mode='widthFix'/>
//確認(rèn)上傳圖片的按鈕
<Button onClick={this.uploadFile}>確認(rèn)上傳證書</Button>  

選擇圖片函數(shù)chooseImage

chooseImage = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original','compressed'],
      sourceType: ['album','camera'],
      success: (res) => {
        tool.showInfo('正在上傳...','loading')
        // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片
        let tempFilePaths = res.tempFilePaths;
        this.setState({
          tempFilePaths: tempFilePaths[0],
        },()=>{
          console.log(tempFilePaths);
        })

      }
    })
  }

上傳圖片函數(shù)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('上傳失敗')
    }
  }

當(dāng)圖片上傳成功后,我們需要展示在頁(yè)面上,沒(méi)上傳圖片之前,需要留白高度400rpx的View,好看些。

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

業(yè)務(wù)中另外的上傳圖片功能需要壓縮圖片,這一塊我做了很久,(現(xiàn)在還是不會(huì)圖片的裁剪,會(huì)做時(shí)補(bǔ)充上來(lái))

//壓縮圖片
 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
            //壓縮比例
            //最大尺寸限制,這里我不知道為什么規(guī)定的320和420無(wú)法壓縮到對(duì)應(yīng)的值,只好/3試試,發(fā)現(xiàn)可以
            let maxW = 320 /3
            let maxH = 420 /3
            //目標(biāo)尺寸
            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));
              }
            }
            //嘗試壓縮文件,創(chuàng)建 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();
            //設(shè)置canvas的長(zhǎng)寬
            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移出屏幕
}

顯示部分與上傳圖片類似,不贅述,當(dāng)有底圖的情況下,不用留白一個(gè)View的位置,直接使用底圖即可。

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容