在Vue中压缩Base64字符串大小并给预览,在这里通过Canvas API来实现:
<template>
<div>
<input type="file" @change="handleFileChange" accept="image/*">
<img :src="previewImage" v-if="previewImage">
</div>
</template>
<script>
export default {
data() {
return {
previewImage: '',// 定义接收、预览图片文件的变量
};
},
methods: {
handleFileChange(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.src = event.target.result;
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 设置压缩后的图片尺寸 自行定义
const maxWidth = 800;
const maxHeight = 800;
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
// 将图片绘制到canvas并导出为Base64图片
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const compressedImage = reader.result;
// 更新预览图片
this.previewImage = compressedImage;
};
}, 'image/jpeg', 0.8);
};
};
reader.readAsDataURL(file);
}
}
};
</script>
这里我们设置最大宽度为800px,最大高度也为800px,然后根据原始图片的尺寸和设置的最大尺寸计算压缩后的尺寸。然后,我们使用Canvas API的toBlob方法将canvas中的图片导出为Blob格式的图片,并将Blob对象传递给FileReader API进行读取。读取完成后,我们将读取结果转换为Base64格式的图片,并将结果赋值给previewImage变量,以便在页面上显示压缩后的预览图片。
请注意,上述示例中的压缩质量为0.8,可以根据实际需求自行修改。另外,由于使用了原生的Canvas和FileReader API,所以需要在Vue组件中使用JavaScript的方式来操作DOM元素。