首先新建一个js文件,并在全局引用,这样方便在使用到的页面随时调用,此方法可以控制是否转base64
/**
* 递归压缩H5图片
* @param url 图片路径
* @param isReturnBase64 是否返回base64
* @param callback 回调函数
* @return
*/
function recursionCompressH5(url, isReturnBase64,callback) {
uni.getImageInfo({
src: url,
success(res) {
let canvasWidth = res.width; //图片原始长宽
let canvasHeight = res.height;
let img = new Image();
img.src = res.path;
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = canvasWidth / 2;
canvas.height = canvasHeight / 2;
ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
canvas.toBlob(function (fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc);
uni.getFileInfo({
filePath: imgSrc,
success: (resFileInfo => {
if (resFileInfo.size > 1024 * 1024 * 0.1) {
//压缩后大于50k就继续压缩
recursionCompressH5(imgSrc, isReturnBase64,callback);
return
} else {
//小于就转化base64
let resultBase64 = canvas.toDataURL("image/png")
uni.hideLoading();
callback && callback(isReturnBase64 ? resultBase64: imgSrc)
}
}),
});
});
}
});
}
module.exports = {
recursionCompressH5:recursionCompressH5
}
调用方法demo
/**
* 点击事件内部调用相机拍照事件
* @param {Object} e
*/
handleFileUpload(item) {
this.name = item.peopleName;
this.peopleId = item.peopleId;
let that = this;
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'],
success: function(res) {
uni.showLoading({
title: '照片上传中',
mask:true
});
that.$img.recursionCompressH5(res.tempFilePaths[0], true, that.imgdata); //调用压缩方法
},
fail: function(res) {
console.log(res);
}
});
},
callback函数即可取到压缩后的图片base64格式
//压缩图片的callback函数
imgdata(data) {
//data就是压缩后的路径
this.urlCode = data;
console.log(this.urlCode);
},