<div>
<input type="file" @change="handleFileChange" accept="image/*">
<img v-if="compressedImage" :src="compressedImage" alt="压缩后的图片">
</div>
const compressedImage = ref(null)
const handleFileChange = (event) => {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = () => {
const img = new Image();
img.src = reader.result;
img.onload = () => {
const maxWidth = 800;
const maxHeight = 600;
const imageWidth = img.width;
const imageHeight = img.height;
let newWidth, newHeight;
if (imageWidth > imageHeight) {
newWidth = maxWidth;
newHeight = (imageHeight / imageWidth) * maxWidth;
} else {
newHeight = maxHeight;
newWidth = (imageWidth / imageHeight) * maxHeight;
}
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
const imgurl = canvas.toDataURL('image/jpeg', 0.2);
compressedImage.value =imgurl
console.log(imgurl,'==1')
};
}
reader.readAsDataURL(file);
}
}