<van-uploader v-model="fileList" multiple :after-read="afterRead" :max-count="" />
2:
afterRead(file){
if(this.fileList.length > ){
this.fileList.splice();
this.$msg({
text:'只能选择这么多!',
type:'info'
})
return false;
} let maxSize = * * ; //自己定义的文件大小,超过多少M就开始压缩(现在是1M)
let fileObj = file.file; // 当前的图片
if (fileObj.size > maxSize) {
this.imgcompress(fileObj, file);
}else{
let Files = this.Files;
Files.push(file.file);
}
},
imgcompress(file, files) {
const img = document.createElement('img')
const reader = new FileReader(); // 读取文件资源实例
reader.readAsDataURL(file); //读取图片资源
reader.onload = e => { //读取成功
img.src = e.target.result;
const { width: originWidth, height: originHeight } = img; //上传的图片的宽高
const maxWidth = , //设置一个canvas 的最大宽高
maxHight = ;
if (originWidth > maxWidth || originHeight > maxHight) {
//计算出图片的缩放比例
if (originWidth > originHeight) {
//宽 大于 高
const Proportion = Math.ceil(originWidth / maxWidth);
let targetWidht = parseInt(originWidth / Proportion); //目标的宽度
let targetHeight = parseInt(originHeight / Proportion); //目标的高度 this.createCanvasCompress(targetWidht, targetHeight, img, files);
} else {
const Proportion = Math.ceil(originHeight / maxHight); //高大于宽
let targetWidht = parseInt(originWidth / Proportion); //目标的宽度
let targetHeight = parseInt(originHeight / Proportion); //目标的高度
let bold = this.createCanvasCompress(
targetWidht,
targetHeight,
img,
files
);
}
} else {
let quality = 0.8;
this.createCanvasCompress(
originWidth,
originHeight,
img,
files,
quality
);
}
};
},
createCanvasCompress(targetWidth, targetHeight, img, files, quality) {
let that = this;
return new Promise((resolve, reject) => {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
// 设置宽高度为等同于要压缩图片的尺寸
canvas.width = targetWidth;
canvas.height = targetHeight;
context.clearRect(, , targetWidth, targetHeight);
//将img绘制到画布上
console.log(targetWidth, targetHeight);
context.drawImage(img, , , targetWidth, targetHeight); let bold = canvas.toBlob(
function(blob) {
resolve(blob);
that.Files.push(blob); //压缩之后的图片
},
"image/png",
quality
);
});
// 创建画布
},