原理就是把图片导入canvas设置宽高再导出
async h5_compressImage(src) {
let _this = this;
return new Promise((resolve, reject) => {
let a = uni.getImageInfo({
src,
success(res) {
console.log('压缩前', res);
let canvasWidth = res.width; // 图片原始宽度
let canvasHeight = res.height; // 图片原始高度
console.log('宽度-', canvasWidth, '高度-', canvasHeight);
let img = new Image();
img.src = res.path;
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
// 这里根据要求限制图片宽高
if (canvasWidth >= 1000) {
canvas.width = canvasWidth * .1;//压缩比例成10%
} else {
canvas.width = canvasWidth;
}
if (canvasHeight >= 1000) {
canvas.height = canvasHeight * .1;//压缩比例成10%
} else {
canvas.height = canvasHeight;
}
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
//toBlob()方法创造Blob对象,用以展示canvas上的图片
canvas.toBlob(function(fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc);
console.log('压缩后的blob路径', imgSrc);
resolve(imgSrc);
});
}
});
然后再想用的地方引用
async uploadFilePromise(url) {
console.log('123', url)
let that = this
that.imagesss = await that.h5_compressImage(url)
// 在这使用方法
return new Promise((resolve, reject) => {
let a = uni.uploadFile({
url: 'https://ylhl.xb-l.com/shows/index/img', // 仅为示例,非真实的接口地址
filePath: that.imagesss,
name: 'pic',
formData: {
pic: url
},
success: (res) => {
var imageurl = JSON.parse(res.data).data;
that.imagearr.push(imageurl)
setTimeout(() => {
resolve(res.data.data)
}, 1000)
console.log(that.fileList1)
}
});
})
},
温馨提示 仅测试了H5端