Files
ai-write-book/scripts/picture.ts
2025-10-08 00:49:47 +08:00

41 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);