小程序,压缩图片
我們在小程序上,直接上傳手機相冊及拍照的圖片時,因為圖片過大(如10m),手機端不像我們再計算機上傳輸那么快,也沒那么穩定,
解決辦法:在圖片上傳前壓縮圖片
壓縮圖片就是將圖片尺寸、圖片質量降低,把這兩個指數降低到合適的規格
1.首先在 wxml 文件中創建一個畫布canvas
<canvas canvas-id="attendCanvasId" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position: absolute;left:-8000px;top:-8000px;" ></canvas>注意:畫布的定位,將它定位到我們看不見的地方?position: absolute; left:-8000px;top:-8000px; ,因為圖片壓縮不需要展示到我們手機屏幕上,大概意思如下圖:
2.就是js處理部分了
思路是:wx的api? 調用相冊或拍照,獲取圖片的size,判斷size大小,如果超過1M就需要壓縮,沒有超過1M那么就不需要壓縮
壓縮,即將圖片尺寸等比減小,并將質量逐步降低,在循環中減小到你覺得合適的尺寸和質量,然后從畫布中取出圖片,上傳到后端服務器中即可
具體代碼如下:
upAvatar: function () {var that = this;wx.chooseImage({count: 1,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],success(res) {wx.showLoading({title: '頭像上傳中',mask: true,});var size = res.tempFiles[0]['size'];if (size > 1048579) { //如果圖片大于1M就要進行壓縮處理//獲取圖片信息wx.getImageInfo({src: res.tempFilePaths[0],success: function (rr) {var ctx = wx.createCanvasContext('attendCanvasId');var ratio = 1;var canvasWidth = rr.widthvar canvasHeight = rr.height;var quality = 0.6; //圖片質量while (canvasWidth > 3000 || canvasHeight > 3000) {//比例取整canvasWidth = Math.trunc(rr.width / ratio)canvasHeight = Math.trunc(rr.height / ratio)ratio += 0.1;}quality = (quality + (ratio / 10)).toFixed(1);if (quality > 1) {quality = 1;}//設置canvas尺寸that.setData({canvasWidth: canvasWidth,canvasHeight: canvasHeight});ctx.drawImage(res.tempFilePaths[0], 0, 0, canvasWidth, canvasHeight); //將圖片填充在canvas上ctx.draw();//下載canvas圖片setTimeout(function () {wx.canvasToTempFilePath({canvasId: 'attendCanvasId',width: 0,height: 0,destWidth: canvasWidth,destHeight: canvasHeight,fileType: 'jpg',quality: quality,success: function success(path) {//這里是將圖片上傳到服務器中that.upAvatar(path.tempFilePath, that); },fail: function fail(e) {wx.hideLoading();wx.showToast({title: '頭像上傳失敗',icon: 'success',duration: 2000});}});}, 1000);}});} else { //小于1M的就不用壓縮了that.upAvatar(res.tempFilePaths[0], that); //上傳圖片到服務器}}})},?
總結
- 上一篇: spwm控制算法c语言实现,SPWM控制
- 下一篇: flex开发的仿pdf阅读器(swfto