49 lines
1.6 KiB
JavaScript
49 lines
1.6 KiB
JavaScript
// 将 _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`
|
|
)
|