van-uploader上传图片压缩
时间: 2023-10-12 14:16:34 浏览: 157
可以使用JavaScript中的canvas API来压缩图片,具体实现可以参考以下代码:
```javascript
function compressImage(file, maxSize) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
let ratio = 1;
// 如果图片宽高大于指定的最大值,则等比例缩放
if (width > maxSize || height > maxSize) {
if (width > height) {
ratio = maxSize / width;
} else {
ratio = maxSize / height;
}
width *= ratio;
height *= ratio;
}
canvas.width = width;
canvas.height = height;
// 在canvas上绘制缩放后的图片
ctx.drawImage(img, 0, 0, width, height);
// 将canvas转为Blob对象
canvas.toBlob((blob) => {
resolve(blob);
}, 'image/jpeg', 0.8); // 0.8为压缩质量,可自由调整
};
img.src = URL.createObjectURL(file);
});
}
```
这个函数接收一个文件对象和一个最大尺寸,会返回一个压缩后的Blob对象,你可以将它上传到服务器。具体使用方法如下:
```javascript
const fileInput = document.getElementById('file-input');
const maxSize = 1024; // 指定最大尺寸为1MB
fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
const compressedFile = await compressImage(file, maxSize);
// 将压缩后的文件上传到服务器
const formData = new FormData();
formData.append('file', compressedFile);
// ... 其他表单数据
await axios.post('/upload', formData);
});
```
阅读全文