compressImage(path) {
//最大高度
const maxHeight = 500;
//最大宽度
const maxWidth = 500;
return new Promise((resolve, reject) => {
let img = new Image();
img.src = path;
img.onload = function () {
const originHeight = img.height;
const originWidth = img.width;
console.log(‘img.height’,img.height)
console.log(‘img.width’,img.width)
let compressedWidth = img.height;
let compressedHeight = img.width;
if ((originWidth > maxWidth) && (originHeight > maxHeight)) {
// 更宽更高,
if ((originHeight / originWidth) > (maxHeight / maxWidth)) {
// 更加严重的高窄型,确定最大高,压缩宽度
compressedHeight = maxHeight
compressedWidth = maxHeight * (originWidth / originHeight)
} else {
//更加严重的矮宽型, 确定最大宽,压缩高度
compressedWidth = maxWidth
compressedHeight = maxWidth * (originHeight / originWidth)
}
} else if (originWidth > maxWidth && originHeight <= maxHeight) {
// 更宽,但比较矮,以maxWidth作为基准
compressedWidth = maxWidth
compressedHeight = maxWidth * (originHeight / originWidth)
} else if (originWidth <= maxWidth && originHeight > maxHeight) {
// 比较窄,但很高,取maxHight为基准
compressedHeight = maxHeight
compressedWidth = maxHeight * (originWidth / originHeight)
} else {
// 符合宽高限制,不做压缩
}
// 生成canvas
let canvas = document.createElement(‘canvas’);
let context = canvas.getContext(‘2d’);
canvas.height = compressedHeight;
canvas.width = compressedWidth;
context.clearRect(0, 0, compressedWidth, compressedHeight);
context.drawImage(img, 100, 100, compressedWidth, compressedHeight);
let base64 = canvas.toDataURL(‘image/*’, 0.8);
resolve(base64)
// let blob = convertBase64UrlToBlob(base64);
// 回调函数返回blob的值。也可根据自己的需求返回base64的值
// resolve(blob)
}
})
},
upload(){
let that = this
uni.chooseImage({
count: 1, //默认9
sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
success: async function (res) {
console.log('res',res)
that.imgUrl = await that.compressImage(res.tempFilePaths[0])
}
});
},