feat: 压缩图片
parent
8d80daaef7
commit
2dca793fa4
@ -0,0 +1,36 @@
|
|||||||
|
const sharp = require('sharp');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const { getInputDir } = require('../utils/index');
|
||||||
|
const { cover } = require('../config/index');
|
||||||
|
|
||||||
|
//工作目录文件夹路径
|
||||||
|
let inputDir = getInputDir();
|
||||||
|
const previewDir = `${inputDir}/预览图`;
|
||||||
|
if (!inputDir || !previewDir) {
|
||||||
|
console.log('未执行裁剪主图功能,工作目录不存在');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reduceImgSize(imgPath, tempImgPath) {
|
||||||
|
let { width } = await sharp(imgPath).metadata();
|
||||||
|
const size = fs.statSync(imgPath).size;
|
||||||
|
const fileSizeInMB = size / (1024 * 1024); // 将字节转换为 MB
|
||||||
|
console.log(width, fileSizeInMB);
|
||||||
|
// .resize(800) // 调整图片宽度为 800 像素
|
||||||
|
// .jpeg({ quality: 80 }) // 设置 JPEG 格式的质量为 80%
|
||||||
|
// .toFile('output.jpg', (err, info) => {
|
||||||
|
// if (err) throw err;
|
||||||
|
// console.log('图片已成功压缩:', info);
|
||||||
|
// });
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.readdirSync(previewDir).forEach(async (file) => {
|
||||||
|
const ext = file.split('.').pop().toLowerCase();
|
||||||
|
if (cover.imgFormat.has(ext)) {
|
||||||
|
const imgPath = path.join(previewDir, file);
|
||||||
|
const tempImgPath = path.join(previewDir, `${file}_temp`);
|
||||||
|
|
||||||
|
reduceImgSize(imgPath, tempImgPath);
|
||||||
|
}
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue