小程序之上传图片压缩
在小程序中上传文件置媒体库中,可能考虑调用的流畅性,需要对视频镜像 压缩处理。
下面是我代码
index.html 页面只是一个简单的按钮选择
1 <view bindtap='aa'>选择图片</view> 2 <canvas canvas-id="photo_canvas" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position: absolute;left:-300px;top:-300px;"></canvas> 3 <!-- <view> 4 未压缩图片 5 <image style="width:{{canvasWidth2}}px;height:{{canvasHeight2}}px;" src='{{aaa}}'></image> 6 </view> 7 <view> 8 压缩图片 9 <image style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;" src='{{bbb}}'></image> 10 </view> --> 11 <view bindtap='bb'>选择视频</view>
index.js
1 Page({ 2 3 /** 4 * 页面的初始数据 5 */ 6 data: { 7 8 }, 9 10 /** 11 * 生命周期函数--监听页面加载 12 */ 13 onLoad: function (options) { 14 15 }, 16 aa(){ 17 var _this=this; 18 wx.chooseImage({ 19 count: 1, 20 sizeType: ['compressed'], 21 success: function (photo) { 22 23 wx.getImageInfo({ 24 src: photo.tempFilePaths[0], 25 success: function (res) { 26 var ctx = wx.createCanvasContext('photo_canvas'); 27 var ratio = 10; 28 var canvasWidth = res.width 29 var canvasHeight = res.height; 30 _this.setData({ 31 aaa: photo.tempFilePaths[0], 32 canvasWidth2: res.width, 33 canvasHeight2: res.height 34 }) 35 // 保证宽高均在200以内 36 while (canvasWidth > 200 || canvasHeight > 200) { 37 //比例取整 38 canvasWidth = Math.trunc(res.width / ratio) 39 canvasHeight = Math.trunc(res.height / ratio) 40 ratio++; 41 } 42 _this.setData({ 43 canvasWidth: canvasWidth, 44 canvasHeight: canvasHeight 45 })//设置canvas尺寸 46 ctx.drawImage(photo.tempFilePaths[0], 0, 0, canvasWidth, canvasHeight) //将图片填充在canvas上 47 ctx.draw() 48 //下载canvas图片 49 setTimeout(function () { 50 wx.canvasToTempFilePath({ 51 canvasId: 'photo_canvas', 52 success: function (res) { 53 console.log(res.tempFilePath) 54 _this.setData({ 55 bbb: res.tempFilePath 56 }) 57 }, 58 fail: function (error) { 59 console.log(error) 60 } 61 }) 62 }, 100) 63 }, 64 fail: function (error) { 65 console.log(error) 66 } 67 }) 68 69 }, 70 error: function (res) { 71 console.log(res); 72 } 73 }) 74 }, 75 bb(){ 76 wx.chooseVideo({ 77 compressed:true, 78 success(e){ 79 console.log(e) 80 } 81 }) 82 }, 83 /** 84 * 生命周期函数--监听页面初次渲染完成 85 */ 86 onReady: function () { 87 88 }, 89 90 /** 91 * 生命周期函数--监听页面显示 92 */ 93 onShow: function () { 94 95 }, 96 97 /** 98 * 生命周期函数--监听页面隐藏 99 */ 100 101 onHide: function () { 102 103 }, 104 105 /** 106 * 生命周期函数--监听页面卸载 107 */ 108 onUnload: function () { 109 110 }, 111 112 /** 113 * 页面相关事件处理函数--监听用户下拉动作 114 */ 115 onPullDownRefresh: function () { 116 117 }, 118 119 /** 120 * 页面上拉触底事件的处理函数 121 */ 122 onReachBottom: function () { 123 124 }, 125 126 /** 127 * 用户点击右上角分享 128 */ 129 onShareAppMessage: function () { 130 131 } 132 })