From 0dcf5f449481ddae29a71c1bdeff5b4662ceadc2 Mon Sep 17 00:00:00 2001 From: dongsk Date: Fri, 16 Oct 2026 16:12:01 +0800 Subject: [PATCH] add scripts/compress-images.mjs --- scripts/compress-images.mjs | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 scripts/compress-images.mjs diff --git a/scripts/compress-images.mjs b/scripts/compress-images.mjs new file mode 100644 index 0000000..81f8907 --- /dev/null +++ b/scripts/compress-images.mjs @@ -0,0 +1,48 @@ +// 将 _source/media 下的原始图片压缩为 webp 输出到 docs/public/media +// 用法: pnpm compress:images +import { readdir, stat, mkdir } from 'node:fs/promises' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import sharp from 'sharp' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) +const root = path.resolve(__dirname, '..') +// 默认读取新版 v8-new 导出图片;如需使用旧版,可在目录中手动切换 +const SRC = path.join(root, '_source', 'v8-new', 'media') +const OUT = path.join(root, 'docs', 'public', 'media') + +const MAX_WIDTH = 1600 // 超过则等比缩放,不放大 +const QUALITY = 82 + +await mkdir(OUT, { recursive: true }) + +const files = (await readdir(SRC)).filter((f) => /\.(png|jpe?g|webp)$/i.test(f)) +let before = 0 +let after = 0 + +for (const file of files) { + const srcPath = path.join(SRC, file) + const base = path.parse(file).name + const outPath = path.join(OUT, `${base}.webp`) + + const input = sharp(srcPath, { failOn: 'none' }) + const meta = await input.metadata() + if (meta.width && meta.width > MAX_WIDTH) { + input.resize({ width: MAX_WIDTH, withoutEnlargement: true }) + } + + const info = await input + .webp({ quality: QUALITY, effort: 5 }) + .toFile(outPath) + + const srcSize = (await stat(srcPath)).size + before += srcSize + after += info.size + console.log( + `${file} ${meta.width}x${meta.height} ${(srcSize / 1024).toFixed(0)}KB -> ${base}.webp ${(info.size / 1024).toFixed(0)}KB` + ) +} + +console.log( + `\n完成 ${files.length} 张:${(before / 1024 / 1024).toFixed(1)}MB -> ${(after / 1024 / 1024).toFixed(1)}MB` +)