有h5和小程序的判断 小程序其实可以直接用sizeType的
// 二分查找法压缩
uni.chooseImage({
count: 1, //默认9
sizeType:['compressed'],
success: (chooseImageRes) => {
console.log(chooseImageRes)
const tempFilePaths = chooseImageRes.tempFilePaths;
const filePath = tempFilePaths[0];
// 获取图片文件大小
uni.getFileInfo({
filePath: filePath,
success: (fileInfo) => {
const fileSize = fileInfo.size; // 图片文件大小,单位为B
// 判断图片大小是否超过200KB
if (fileSize > 200 * 1024) {
#ifdef H5
//h5压缩图片
const targetSizeKB = 200; // 设置目标文件大小,单位为KB,根据需求调整
that.compressH5(chooseImageRes.tempFiles[0],targetSizeKB).then(file => {
console.log('file 222 = ', file)
uni.uploadFile({
url: envChange(true) + '/oss/upFile', //上传图片的后端接口
file: chooseImageRes.tempFiles[0],// res.tempFilePaths[0],
name: 'upfile',
success: res => {
const imgUrl = res.data && JSON.parse(res.data).url
// that.toOrderAjax(data, imgUrl)
}
})
// this.uploadCompressedImage(file);
}).catch(err => {
console.log('catch', err)
})
#endif
// //#ifdef APP-PLUS || MP-WEIXIN
// // 如果超过200KB,进行压缩
// uni.compressImage({
// src: filePath,
// quality: 10, // 设置压缩质量(0-100)- 根据需求进行调整
// success: (compressRes) => {
// // 压缩成功后的逻辑
// this.uploadCompressedImage(compressRes.tempFilePath);
// },
// fail: (err) => {
// console.error('压缩图片失败:', err);
// uni.showToast({
// title: '压缩图片失败,请重试',
// icon: 'none'
// });
// }
// });
// //#endif
} else {
// 如果未超过200KB,直接上传原图
console.log('未超过200KB',filePath)
// this.uploadCompressedImage(filePath);
}
},
fail: (err) => {
console.error('获取文件信息失败:', err);
uni.showToast({
title: '获取文件信息失败,请重试',
icon: 'none'
});
}
});
},
fail: (err) => {
console.error('选择图片失败:', err);
uni.showToast({
title: '选择图片失败,请重试',
icon: 'none'
});
}
});
compressH5(fileItem, targetSizeKB, initialQuality = 1.0) {
const maxQuality = 1.0;
const minQuality = 0.0;
const tolerance = 0.01; // 根据需要调整公差
return new Promise((resolve, reject) => {
const binarySearch = (min, max) => {
const midQuality = (min + max) / 2;
const reader = new FileReader();
reader.readAsDataURL(fileItem);
reader.onload = function () {
const img = new Image();
img.src = this.result;
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// 使用异步的 toBlob 方法
canvas.toBlob(async (blob) => {
const fileSizeKB = blob.size / 1024;
if (Math.abs(fileSizeKB - targetSizeKB) < tolerance || max - min < tolerance) {
// 当前质量足够接近目标大小,使用当前质量解析
resolve(URL.createObjectURL(blob));
} else if (fileSizeKB > targetSizeKB) {
// 如果文件大小太大,降低质量,继续二分查找
binarySearch(min, midQuality);
} else {
// 如果文件大小太小,增加质量,继续二分查找
binarySearch(midQuality, max);
}
}, 'image/jpeg', midQuality);
};
};
reader.onerror = function (error) {
reject(error);
};
};
// 开始二分查找
binarySearch(minQuality, maxQuality);
});
},