组件
<el-upload
:before-upload="onBeforeUpload"
>
原图片宽高按比例压缩
async onBeforeUpload(file) {
const isJPG =
file.type === "image/png" ||
file.type === "image/jpg" ||
file.type === "image/jpeg" ||
file.type === "image/webp";
if (!isJPG) {
this.$message.error("图片格式不正确!");
return false;
}
const { width: oriWidth, height: oriHeight } = await this.getImageDimensions(
URL.createObjectURL(file)
);
const compressFile = new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (e) => {
const img = new Image();
img.src = e.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 按原图80%的比例压缩,根据自己需求决定
canvas.width = oriWidth * 0.8; // 设置压缩后图片的宽度
canvas.height = oriHeight * 0.8; // 根据原始图片比例计算压缩后图片的高度度
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
const compressedFile = new File([blob], file.name, { type: file.type, lastModified: Date.now() });
resolve(compressedFile);
}, file.type);
};
};
});
const fileRes = await compressFile;
// 压缩之后图片大mb报错
const isLt5MB = fileRes.size / 1024 / 1024 < 5;
if (!isLt5MB) {
this.$message.error("上传图片大小太大!");
return false;
} else {
return compressFile;
}
},
// 拿到原图片宽高方法
getImageDimensions(imageUrl) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const width = img.width;
const height = img.height;
// 解析Promise,并传递宽度和高度(如果需要的话)
resolve({ width, height });
};
img.onerror = () => {
// 处理图片加载错误
console.error("图片加载失败");
resolve(null); // 或者根据需要拒绝Promise
};
img.src = imageUrl;
});
},