小程式把圖片轉換成base64

kimingw發表於2018-09-05

1、首先需要到upng.js,然後upng.js需要pako.js,先一併下載了

2、然後就可以直接用了,具體程式碼如下:

<!--pages/base/base.wxml-->
<canvas class='canvas' id='scannerCanvas' canvas-id='scannerCanvas' disable-scroll="true" style="height:{{height}}px;width:{{width}}px"/>
<view class="btns">
  <view bindtap="chooseImg">選擇</view>
  <view>確定</view>
</view>
<text>{{time}}</text>

 

// js

const upng = require('../../utils/UPNG.js');

Page({

  /**
   * 頁面的初始資料
   */
  data: {
    width:360,
    height:360,
    time:""
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function () {
    wx.getSystemInfo({
      success: res => {
        this.setData({ 
          height: res.windowHeight-80,
          width: res.windowWidth
        });
      }
    });
  },
  
  // 選擇照片
  chooseImg:function(){
    var start = (new Date()).getTime()
    wx.chooseImage({
      count:1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths[0]
        var canvas = wx.createCanvasContext('scannerCanvas')
        // 1. 繪製圖片至canvas
        canvas.drawImage(tempFilePaths, 0, 0, this.data.width, this.data.height )
        // 繪製完成後執行回撥,API 1.7.0
        canvas.draw(false, () => {
          // 2. 獲取影象資料, API 1.9.0
          wx.canvasGetImageData({
            canvasId: 'scannerCanvas',
            x: 0,
            y: 0,
            width: this.data.width,
            height: this.data.height,
            success : (res) => {
              let platform = wx.getSystemInfoSync().platform
              if (platform == 'ios') {
                // 相容處理:ios獲取的圖片上下顛倒
                res = this.reverseImgData(res)
              }
              // 3. png編碼
              let pngData = upng.encode([res.data.buffer], this.data.width, this.data.height)   
              // 4. base64編碼
              let base64 = wx.arrayBufferToBase64(pngData)
              this.setData({
                time:(new Date()).getTime()-start
              })
            }
          })
        })
      }
    })
  },
  
  // 圖片顛倒
  reverseImgData(res) {
    var w = res.width
    var h = res.height
    let con = 0
    for (var i = 0; i < h / 2; i++) {
      for (var j = 0; j < w * 4; j++) {
        con = res.data[i * w * 4 + j]
        res.data[i * w * 4 + j] = res.data[(h - i - 1) * w * 4 + j]
        res.data[(h - i - 1) * w * 4 + j] = con
      }
    }
    return res
  },
})

 

/* wxss */
.btns{
  display: flex;
}
.btns>view{
  width: 50%;
  text-align: center;
  line-height: 50px;
}
.btns>view:first-child{
  border-right: 2rpx solid #ddd;
  box-sizing: border-box;
}
text{
  text-align: center;
  width: 100%;
  line-height: 30px;
  display:block;
}

  

相關文章