1、获取图片宽度、高度,并重置图片的宽度和高度;这里只用图片的宽度来做判断。下面代码只是一些代码片段。
uni.getImageInfo({
src: file.path,
success: function (res) {
let canvasWidth = res.width //图片原始长宽
let canvasHeight = res.height;
let base = canvasWidth/canvasHeight;
if(canvasWidth>500){
canvasWidth = 500;
canvasHeight = Math.floor(canvasWidth/base);
}
2、使用canvas重新绘制图片。
let img = new Image();
img.src = file.path; // 要压缩的图片
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);
3、生成文件,然后下载文件,并获取到路径
canvas.toBlob(function (fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc);//原生JS生成文件路径
uni.downloadFile({
url: imgSrc, //仅为示例,并非真实的资源
success: (resFilePath) => {
if (resFile.statusCode === 200) {
resolve(resFilePath);
}
}
});
});