最近把app转成h5后,发现图片不能自动压缩。现在手机像素高,拍照都是5m左右的,这样的图片上传速度极慢。在社区里找了好久,发现可用的不多,我专门研究了下,分享代码,当前测试点不多,不排除有bug。
test: function(){
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['camera'],
success: async function (res) {
const tempFilePaths = res.tempFilePaths;
let img = '';
/* #ifdef H5 */
img = await this.comprossImage(tempFilePaths[0])
/* #endif */
uni.uploadFile({
url: server + '/....',
filePath: img || tempFilePaths[0],
name: 'file',
success: (uploadFileRes) => {
let json = JSON.parse(uploadFileRes.data);
if(1 ==json.state){
// 上传成功
}else{
// 上传失败
}
},
fail: function(err) {
//其它错误
}
});
}
});
},
comprossImage: async function(imgSrc,maxWidth) {
if(!imgSrc) return 0;
return new Promise((resolve, reject) => {
maxWidth = maxWidth || 1024;/*默认压缩成1024宽*/
uni.getImageInfo({
src: imgSrc,
success(res) {
if(res.width <= maxWidth){/*太小的图片就不压缩了*/
resolve(imgSrc);
return;
}
let img = new Image();
img.src = res.path;
let canvas = document.createElement('canvas');
let scale = res.width / res.height;
let ctx = canvas.getContext('2d');
canvas.width = maxWidth;
canvas.height = maxWidth / scale;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
/* 默认图片质量为0.7 */
var quality = 0.7;
/* 回调函数返回base64的值 */
var base64 = canvas.toDataURL('image/jpeg', quality);
resolve(base64);
}
});
})
},
2 个评论
要回复文章请先登录或注册
妖妖零
妖妖零