js压缩图片到指定大小
时间: 2023-08-06 08:02:20 浏览: 151
你可以使用JavaScript中的canvas API来压缩图片。下面是一个示例代码,将图片压缩到指定大小:
```javascript
function compressImage(file, maxSize, callback) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const img = new Image();
img.src = event.target.result;
img.onload = function () {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
let scale = 1;
if (width > height && width > maxSize) {
scale = maxSize / width;
width = maxSize;
height *= scale;
} else if (height > maxSize) {
scale = maxSize / height;
height = maxSize;
width *= scale;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(function (blob) {
callback(blob);
}, file.type);
};
};
}
```
调用示例:
```javascript
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', function () {
const file = fileInput.files[0];
compressImage(file, 1024, function (blob) {
console.log('压缩后的文件大小:', blob.size);
// 使用压缩后的图片
});
});
```
其中,`compressImage`函数中的参数含义如下:
- `file`:要压缩的图片文件对象。
- `maxSize`:压缩后图片的最大大小(单位:字节)。
- `callback`:压缩完成后的回调函数,参数为压缩后的图片文件对象。
注意:使用canvas来处理大图会消耗较多的内存,因此建议对于大图先进行等比缩小再进行压缩。