1. 程式人生 > >小程式之上傳圖片壓縮

小程式之上傳圖片壓縮

在小程式中上傳檔案置媒體庫中,可能考慮呼叫的流暢性,需要對視訊映象 壓縮處理。

下面是我程式碼

index.html  頁面只是一個簡單的按鈕選擇



<view bindtap='aa'>選擇圖片</view><canvas canvas-id="photo_canvas" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position: absolute;left:-300px;top:-300px;"></canvas><!-- <view>未壓縮圖片<image style="width:{{canvasWidth2}}px;height:{{canvasHeight2}}px;" src='{{aaa}}'></image>
</view><view>壓縮圖片<image style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;" src='{{bbb}}'></image></view> --><view bindtap='bb'>選擇視訊</view>

index.js

Page({
/** * 頁面的初始資料 */ data: { },
/** * 生命週期函式--監聽頁面載入 */ onLoad: function (options) { },aa(){
var _this=this; wx.chooseImage({ count: 1, sizeType: ['compressed'], success: function (photo) { wx.getImageInfo({ src: photo.tempFilePaths[0], success: function (res) { var ctx = wx.createCanvasContext('photo_canvas'); var ratio = 10; var canvasWidth =
res.width var canvasHeight = res.height; _this.setData({ aaa: photo.tempFilePaths[0], canvasWidth2: res.width, canvasHeight2: res.height }) // 保證寬高均在200以內 while (canvasWidth > 200 || canvasHeight > 200) { //比例取整 canvasWidth = Math.trunc(res.width / ratio) canvasHeight = Math.trunc(res.height / ratio) ratio++; } _this.setData({ canvasWidth: canvasWidth, canvasHeight: canvasHeight })//設定canvas尺寸 ctx.drawImage(photo.tempFilePaths[0], 0, 0, canvasWidth, canvasHeight) //將圖片填充在canvas上 ctx.draw() //下載canvas圖片 setTimeout(function () { wx.canvasToTempFilePath({ canvasId: 'photo_canvas', success: function (res) { console.log(res.tempFilePath) _this.setData({ bbb: res.tempFilePath }) }, fail: function (error) { console.log(error) } }) }, 100) }, fail: function (error) { console.log(error) } })
}, error: function (res) { console.log(res); } })},bb(){wx.chooseVideo({ compressed:true, success(e){ console.log(e) }})}, /** * 生命週期函式--監聽頁面初次渲染完成 */ onReady: function () { },
/** * 生命週期函式--監聽頁面顯示 */ onShow: function () { },
/** * 生命週期函式--監聽頁面隱藏 */ onHide: function () { },
/** * 生命週期函式--監聽頁面解除安裝 */ onUnload: function () { },
/** * 頁面相關事件處理函式--監聽使用者下拉動作 */ onPullDownRefresh: function () { },
/** * 頁面上拉觸底事件的處理函式 */ onReachBottom: function () { },
/** * 使用者點選右上角分享 */ onShareAppMessage: function () { }})