app.Upload.imgCompress({
'files': [this.data.imgSrc],
'canvasId': 'canvas',
'that': this
}).then(res => {
console.log(res) // [url,...]
})
/**
* canvas 压缩图片
* @param files 图片url集合
* @param canvasId canvas 的 id
* @param that this
*/
imgCompress({ files, canvasId, that }) {
// <canvas class="canvas" canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;"></canvas>
return new Promise((resolve, reject) => {
if(files && Array.isArray(files) && files.length > 0) {
let promiseList = [];
files.map((item, index) => {
promiseList[index] = new Promise((resolve, reject) =>{
wx.getImageInfo({
src: item,
success: function(res) {
let cW = res.width, cH = res.height;
let cWidth = cW,cHeight= cH;
if ((cW / cH)<0.56){ //说明 要依高为缩放比例--0.56是 750/1334的结果
if (cH>1334){
cHeight = 1334;
cWidth = (cW * 1334) / cH;
}
} else {//要依宽为缩放比例
if (cW > 750) {
cWidth = 750;
cHeight = (cH * 750) / cW;
}
}
console.log(parseInt(cWidth), parseInt(cHeight));//计算出缩放后的宽 高
that.setData({ cWidth: cWidth, cHeight: cHeight});//让canvas大小和要缩放的图片大小一致
let imageW = cWidth, imageH = cHeight, imagePath = res.path;
const ctx = wx.createCanvasContext(canvasId);
ctx.drawImage(imagePath, 0, 0, cW, cH, 0, 0, imageW, imageH);
ctx.draw(false, setTimeout(function () { // 一定要加定时器,因为ctx.draw()应用到canvas是有个时间的
wx.canvasToTempFilePath({
fileType:'jpg',
canvasId: canvasId,
x: 0,
y: 0,
width: imageW,
height: imageH,
destWidth: imageW,
destHeight: imageH,
quality: 1,
success: function (res) {
console.log(res.tempFilePath)
resolve(res.tempFilePath)
},
fail: function (error) {
console.log(error);
reject(error);
}
});
}, 200));
}
})
})
})
Promise.all(promiseList).then((result) => {
resolve(result)
})
}else {
reject('参数错误')
}
})
}