需求
博客目录里塞了几百张截图,PNG 动辄 1–2 MB。想要的是:
- 递归处理整个目录;
- 保留子目录结构;
- 跳过已经转换过的文件;
- 体积对比打印出来。
代码
from pathlib import Path
from PIL import Image
SRC = Path("img")
DST = Path("img-webp")
for src in SRC.rglob("*"):
if src.suffix.lower() not in {".png", ".jpg", ".jpeg", ".webp"}:
continue
dst = DST / src.relative_to(SRC).with_suffix(".webp")
if dst.exists():
continue
dst.parent.mkdir(parents=True, exist_ok=True)
with Image.open(src) as im:
im.save(dst, "WEBP", quality=82, method=6)
a, b = src.stat().st_size, dst.stat().st_size
print(f"{src} {a//1024}KB -> {b//1024}KB")
参数的选择
- quality 82:截图和照片的折中点。低于 75 时文字边缘开始糊;
- method 6:压缩算法的最慢档,体积能再小 5–10%,批量跑可以接受;
- 动图不要走这条路径,
Image.open只会拿到第一帧。
结果
截图类平均掉了 70%,风景照大约 55%。首屏从 3.2 MB 降到 900 KB 左右。
别忘了
WebP 在旧版 Safari 之外基本没有兼容问题,但如果要长期存档,原图仍建议保留一份。