因为uniapp H5不能使用官方的 uni.compressImage api进行压缩 ,所以采用canvas画布的方式将图片渲染在canvas中调整大小以达到压缩的目的
uni.chooseImage({
count:1,
success: (res) => {
this.img = res.tempFilePaths[0] //这个就是图片的路径
}
})
uni.getImageInfo({
src:imgsrc, //图片路径
success: (res) => {
let canvasWidth = res.width //图片原始长宽
let canvasHeight = res.height;
let base = canvasWidth/canvasHeight;
if(canvasWidth>500){ //如果宽度大于设定的500宽度值
canvasWidth = 500; //设定最大宽度
canvasHeight = Math.floor(canvasWidth/base);
}
}
})
// 使用canvas重新绘制图片
let img = new Image();
img.src = imgsrc; // 要压缩的图片
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
// 将图片画到canvas上面 使用Canvas压缩
ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
4.最后一步,生成文件,然后下载文件,并获取到解压后的路径
// 生成文件,然后下载文件,并获取到路径
canvas.toBlob(function(fileSrc){
let imgSrc = window.URL.createObjectURL(fileSrc);//原生JS生成文件路径
uni.downloadFile({
url:imgSrc,
success:(resFilePath)=>{
//报错判断
if (resFilePath.statusCode === 200) {
console.log('结果',resFilePath.tempFilePath)
that.img2 = resFilePath.tempFilePath
}
}
})
})
经测试用此方法可以将4MB的照片压缩到400kb左右,可以自行调整压缩效率 ,过大的图片还没试过,各位可以尝试一下