?壓縮圖片原地址https://my.oschina.net/u/3362856/blog/1162498
chooseImage: function (e) {//上傳照片
? var that = this;
? wx.chooseImage({
? ? count:1,//最多可以選擇的圖片張數(shù),默認9
? ? sizeType: [ 'compressed'], // 可以指定是原圖還是壓縮圖蜒程,默認二者都有
? ? sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機位岔,默認二者都有
? ? success: function (res) {
? ? ? // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片
? ? ? that.setData({
? ? ? ? files: res.tempFilePaths[0]
? ? ? });
? ? }
? })
},
drawCanvas:function(){// 縮放圖片
? const ctx = wx.createCanvasContext('attendCanvasId');
? let that=this;
? wx.getImageInfo({
src: that.data.files,
? ? success:function (res) {
if(res.width>500||res.height>500){//判斷圖片是否超過500像素
? ? ? ? let scale=res.width/res.height//獲取原圖比例
? ? ? ? that.setData({//構造畫板寬高
? ? ? ? ? canWidth:500,
? ? ? ? ? canHeight:500/scale
})
//畫出壓縮圖片
? ? ? ? ctx.drawImage(that.data.files, 0, 0, that.data.canWidth, that.data.canHeight);
? ? ? ? ctx.draw();
? ? ? ? //等待壓縮圖片生成
? ? ? ? var st =setTimeout(function(){
that.prodImageOpt();
? ? ? ? ? clearTimeout(st);
? ? ? ? },3000);
? ? ? }else{
//上傳圖片
? ? ? ? that.uploadFileOpt(that.data.files);
? ? ? }
}
})
},
prodImageOpt:function(){// 獲取壓縮圖片路徑
? var that =this;
? wx.canvasToTempFilePath({
canvasId:'attendCanvasId',
? ? success:function success(res) {
// 上傳圖片
? ? ? that.uploadFileOpt(res.tempFilePath);
? ? },
? });
},
uploadFileOpt:function(path){//上傳圖片
? let that=this;
? wx.uploadFile({
url:'/api/uploadPath', //后臺上傳api路徑
? ? filePath: path,
? ? name:'file',
? ? success:function(res){
console.log(res);//因uploadFile無法在network中捕獲故需打印返回內容
? ? ? //to do
? ? },
? ? fail:e=>{
//to do
? ? }
})
}