<template>
<div>
<el-upload
class="upload-demo"
action=""
:show-file-list="false"
:before-upload="beforeUpload"
:on-success="handleSuccess"
>
<el-button size="small" type="primary">点击上传图片</el-button>
</el-upload>
<canvas ref="canvas" style="display: none;"></canvas>
<el-image
v-if="imageUrl"
:src="imageUrl"
style="max-width: 300px; margin-top: 20px;"
></el-image>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: null,
};
},
methods: {
beforeUpload(file) {
return new Promise((resolve) => {
this.compressImage(file)
.then((compressedFile) => {
resolve(compressedFile);
})
.catch((error) => {
console.error('图片压缩失败:', error);
resolve(false);
});
});
},
handleSuccess(response) {
// 处理上传成功后的操作,这里省略具体代码
console.log('上传成功', response);
},
compressImage(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const image = new Image();
image.onload = () => {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const maxSize = 800; // 设置最大宽高,根据需要调整
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0, width, height);
canvas.toBlob(
(blob) => {
const compressedFile = new File([blob], file.name, {
type: file.type,
lastModified: file.lastModified,
});
resolve(compressedFile);
},
file.type,
0.7 // 0.7表示压缩质量,可以根据需要调整
);
};
image.src = e.target.result;
};
reader.readAsDataURL(file);
});
},
},
};
</script>
<style>
.upload-demo {
border: 1px dashed #409eff;
border-radius: 6px;
padding: 20px;
text-align: center;
cursor: pointer;
}
</style>
在上传之前,通过before-upload属性调用beforeUpload方法,该方法使用Canvas对图片进行压缩。在compressImage方法中,我们读取用户选择的图片,绘制到Canvas上并调整尺寸,然后使用canvas.toBlob()将Canvas中的图片导出为Blob对象,最后将Blob对象封装为一个新的File对象,将其传递给before-upload方法,实现图片压缩