js图片压缩
时间: 2023-08-06 21:14:36 浏览: 42
可以使用canvas来进行图片压缩。以下是一个基本的示例代码:
```javascript
// 压缩图片
function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(event) {
const img = new Image();
img.src = event.target.result;
img.onload = function() {
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height = height * maxWidth / width;
width = maxWidth;
}
if (height > maxHeight) {
width = width * maxHeight / height;
height = maxHeight;
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(function(blob) {
resolve(blob);
}, file.type || 'image/png', quality);
};
};
reader.onerror = function(error) {
reject(error);
};
});
}
```
以上代码会将图片压缩到指定的最大宽度和高度,并且可以通过quality参数控制图片质量。使用时,调用该函数并传入需要压缩的图片文件、最大宽度、最大高度和质量参数即可。
```javascript
const fileInput = document.querySelector('input[type=file]');
fileInput.addEventListener('change', async function(event) {
const file = event.target.files[0];
const compressedBlob = await compressImage(file, 800, 600, 0.7);
console.log(compressedBlob);
});
```