js压缩图片到指定大小
时间: 2023-09-06 09:11:31 浏览: 54
你可以使用 HTML5 中的 Canvas 元素和 File API 来实现 JavaScript 压缩图片到指定大小的功能。以下是一个简单的示例代码:
```javascript
function compressImage(file, maxSize, callback) {
var reader = new FileReader();
reader.onload = function() {
var img = new Image();
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width = img.width;
var height = img.height;
var ratio = 1;
if (width > height) {
if (width > maxSize) {
ratio = maxSize / width;
}
} else {
if (height > maxSize) {
ratio = maxSize / height;
}
}
width *= ratio;
height *= ratio;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(function(blob) {
callback(blob);
}, 'image/jpeg', 0.8);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
}
```
这个函数接受三个参数:
1. `file`:要压缩的图片文件。
2. `maxSize`:压缩后的图片最大尺寸,单位为像素。
3. `callback`:压缩完成后的回调函数,接受压缩后的 Blob 对象作为参数。
使用示例:
```javascript
var fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', function() {
var file = fileInput.files[0];
compressImage(file, 800, function(blob) {
// 压缩完成后的处理逻辑
});
});
```
这个示例将选中的图片文件压缩到最大宽度或高度为 800 像素,压缩质量为 80% 的 JPEG 格式,并将压缩后的 Blob 对象传递给回调函数进行处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)