nodejs 压缩超过5M图片代码
时间: 2023-07-03 17:33:52 浏览: 64
以下是使用Node.js的sharp库进行超过5M图片压缩的示例代码:
```javascript
const sharp = require('sharp');
const fs = require('fs');
function compressImage(inputPath, outputPath, maxSize) {
// 获取原始图片尺寸
sharp(inputPath)
.metadata()
.then(metadata => {
const { width, height } = metadata;
// 根据最大尺寸计算压缩比例
const ratio = (width * height) / (maxSize * 1000);
// 如果图片已经小于指定尺寸,则不需要进行压缩
if (ratio <= 1) {
sharp(inputPath).toFile(outputPath, (err) => {
if (err) throw err;
});
return;
}
// 计算新的尺寸
const newWidth = Math.floor(width / ratio);
const newHeight = Math.floor(height / ratio);
// 进行压缩并保存
sharp(inputPath)
.resize(newWidth, newHeight, { withoutEnlargement: true })
.toFile(outputPath, (err) => {
if (err) throw err;
});
})
.catch(err => {
console.error(err);
});
}
```
使用示例:
```javascript
compressImage("input.jpg", "output.jpg", 5000); // 压缩到5MB以下
```
在此示例中,我们首先使用sharp库的metadata方法获取输入图片的宽度和高度,然后根据指定的最大尺寸计算压缩比例。如果原始图片已经小于指定尺寸,则直接保存输出图片。否则,我们根据计算出的压缩比例,计算出新的尺寸并进行压缩,最后使用toFile方法保存输出图片。请注意,我们在resize方法中传入了`withoutEnlargement: true`参数,以确保不会对原始图片进行放大。