yasuoItem(img) { //压缩单张图片
return new Promise((resolve, reject) => {
uni.getImageInfo({ //获取图片信息
src: img,
success: (res) => {
var ratio = parseFloat(res.width / res.height); //获得图片实际的宽高比
var width = res.width;
var height = res.height;
var maxwh = this.maxwh;
var maxhh = this.maxhh;
if (width > maxwh) {
width = maxwh;
height = parseInt(width / ratio);
} else if (height > maxhh) {
height = maxhh;
width = parseInt(height * ratio);
}
this.imageW = width;
this.imageH = height;
this.$nextTick(function(){ //保证页面canvas组件的宽高已生效再操作画布(避免图片不全问题)
var ctx = uni.createCanvasContext('myCanvas', this); // 将图片写入画布
ctx.clearRect(0, 0, width, height); //清空画布,避免透明图片显示上一张图片的底色
ctx.drawImage(res.path, 0, 0, width, height);
ctx.draw(true, (e) => { // 获取画布要裁剪的位置和宽度 均为百分比 * 画布中图片的宽度
var fileType = res.path.replace(/^.+\./, '');
if (fileType == 'png') {
fileType = 'png';
} else {
fileType = 'jpg';
}
//把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径。
uni.canvasToTempFilePath({
x: 0,
y: 0,
width: width,
height: height,
destWidth: width,
destHeight: height,
quality: this.quality,
canvasId: 'myCanvas',
fileType: fileType,
success: (res2) => {
// res 图片信息 res2压缩后的图片信息
res2.oldWidth = res.width;
res2.oldHeight = res.height;
res2.width = width;
res2.height = height;
res2.path = res.path;
res2.fileType = fileType;
resolve(res2)
}
}, this);
});
})
}
})
})
},
yasuoImg(imgs, val) { //压缩多张图片
var val = val || [];
var imgs = imgs;
return new Promise((resolve, reject) => {
var resolves = resolves || resolve;
if (typeof imgs == 'object') {
if (imgs.length) {
this.yasuoItem(imgs[0]).then(e => {
val.push(e)
var imgs2 = [];
for (var i = 0; i < imgs.length; i++) {
if (i != 0) {
imgs2.push(imgs[i])
}
}
this.yasuoImg(imgs2, val).then(e => {
resolve(e)
})
})
} else {
resolve(val)
this.$emit("changes", val);
}
} else {
this.yasuoImg(imgs).then(e => {
resolve(val)
this.$emit("changes", val);
})
}
})
}
uni-app压缩多张图片
最新推荐文章于 2024-04-17 09:38:17 发布