微信小程式呼叫攝像頭,實現圖片壓縮上傳
阿新 • • 發佈:2019-01-23
這篇文章主要為大家詳細介紹了微信小程式實現圖片壓縮功能,具有一定的參考價值,感興趣的小夥伴們可以參考一下,下面直接上程式碼
先是wxml:
<view bindtap='takePictures'>選擇圖片</view>
<canvas canvas-id="attendCanvasId" style="width:300px;height:300px;position: absolute;left:-300px;top:-300px"></canvas>
<image src="{{attendSuccessImg}}"></image>
下面是js
Page({ /** * 頁面的初始資料 */ data: { attendSuccessImg: "", canvasImgUrl:'', src:"" }, /** * 生命週期函式--監聽頁面載入 */ onLoad: function(options) {}, // 點選照相 takePictures: function () { var that = this; wx.chooseImage({ count: 1, // 預設9 sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有 // 可以指定來源是相簿還是相機,預設二者都有 success: function (res) { // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片 var tempFilePaths = res.tempFilePaths; that.setData({ attendSuccessImg: tempFilePaths[0] }); // 上傳圖片 //判斷機型 var model = ""; wx.getSystemInfo({ success: function (res) { var that = this; model = res.model; } }) if (model.indexOf("iPhone") <= 0) { // that.uploadFileOpt(that.data.attendSuccessImg); console.log(111111) } else { drawCanvas(); } // 縮放圖片 function drawCanvas() { const ctx = wx.createCanvasContext('attendCanvasId'); ctx.drawImage(tempFilePaths[0], 0, 0, 94, 96); ctx.draw(); that.prodImageOpt(); } } }); }, // 生成圖片 prodImageOpt: function () { var that = this; wx.canvasToTempFilePath({ canvasId: 'attendCanvasId', success: function success(res) { that.setData({ canvasImgUrl: res.tempFilePath }); // 上傳圖片 that.uploadFileOpt(that.data.canvasImgUrl); }, complete: function complete(e) { } }); }, })