提升用户体验:Vue与compressor.js实现高效文件压缩
<template>
<div>
<input type="file" @change="compressImage" multiple>
<div v-for="(img, index) in compressedImages" :key="index">
<img :src="img" alt="Compressed Image">
</div>
</div>
</template>
<script>
export default {
data() {
return {
compressedImages: []
};
},
methods: {
compressImage(event) {
this.compressImages(event.target.files);
},
compressImages(files) {
files.forEach(file => {
if (file.type.match(/image.*/)) {
this.compressImageFile(file, this.convertToImage, this.compressAndResize);
} else {
console.log('Not an image file');
}
});
},
compressImageFile(file, ...funcs) {
const promise = new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => {
resolve(e.target.result);
};
reader.onerror = error => {
reject(error);
};
reader.readAsDataURL(file);
});
promise.then(image => {
funcs.reduce((promise, func) => promise.then(func), image);
});
},
convertToImage(dataUrl) {
return fetch(dataUrl)
.then(response => response.blob())
.then(blob => createImageBitmap(blob));
},
compressAndResize(image) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const width = image.width;
const height = image.height;
canvas.width = width;
canvas.height = height;
ctx.drawImage(image, 0, 0, width, height);
return canvas.toDataURL('image/jpeg', 0.7);
}
}
};
</script>
这段代码使用Vue.js创建了一个简单的用户界面,其中包含一个文件输入框和一个用于展示压缩后图片的列表。当用户选择文件后,compressImage
方法被触发,它调用 compressImages
方法,后者对每个选中的图片文件进行压缩处理。compressImageFile
方法用于处理文件读取和压缩过程的异步操作,convertToImage
和 compressAndResize
分别用于将文件转换为图片并进行压缩。
评论已关闭