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; }