41 lines
1.3 KiB
TypeScript
41 lines
1.3 KiB
TypeScript
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import sharp from 'sharp';
|
||
|
||
const root = path.join(process.cwd(), 'public','assets', 'daily');
|
||
|
||
// 获取 root 目录下的所有图片,然后把图片的大小调整小一点,在 500k-1M 之间,放回原名。
|
||
const zipPicture = async (root: string) => {
|
||
const files = fs.readdirSync(root);
|
||
for (const file of files) {
|
||
const filePath = path.join(root, file);
|
||
const stat = fs.statSync(filePath);
|
||
if (stat.isFile() && /\.(jpg|jpeg|png)$/i.test(file)) {
|
||
let buffer = fs.readFileSync(filePath);
|
||
let size = buffer.length;
|
||
if (size > 1024 * 1024) { // 超过1M才压缩
|
||
let quality = 80;
|
||
let compressedBuffer;
|
||
do {
|
||
compressedBuffer = await sharp(buffer)
|
||
.jpeg({ quality })
|
||
.toBuffer();
|
||
size = compressedBuffer.length;
|
||
quality -= 10;
|
||
} while (size > 1024 * 1024 && quality > 30);
|
||
|
||
if (size < 500 * 1024) {
|
||
// 如果压缩后小于500k,适当提高质量
|
||
quality += 5;
|
||
compressedBuffer = await sharp(buffer)
|
||
.jpeg({ quality })
|
||
.toBuffer();
|
||
}
|
||
fs.writeFileSync(filePath, compressedBuffer);
|
||
console.log(`${file} 压缩后大小: ${(compressedBuffer.length / 1024).toFixed(2)} KB`);
|
||
}
|
||
}
|
||
}
|
||
};
|
||
|
||
zipPicture(root); |