WebP 批量转换
痛点
美术素材的 PNG 一次拍下来就是几十 MB。每个 PNG 1.5MB 起步。一组 18 张图,原始就是 30+MB。
WebP 是 Google 推出的图片格式,相同画质下比 PNG 小 70% 左右。
工具
cwebp(libwebp):命令行,单独工具- Pillow:Python 库,集成方便
- Squoosh:浏览器工具,一次只能转一张
推荐 Pillow——可以写脚本批量处理,可控粒度高。
脚本
from PIL import Image
from pathlib import Path
PLAN = [
# (relative_path, quality, max_width, drop_png)
("theme/home-bg-large.png", 78, 1920, True),
("posts/cover.png", 82, 1200, True),
("home/hero-bg-blur.png", 60, 800, False), # 模糊用低质量
("player/cover.png", 85, 800, False), # 透明 PNG 保留
# ...
]
for rel, q, max_w, drop in PLAN:
src = Path(rel)
img = Image.open(src)
if img.width > max_w:
img = img.resize((max_w, int(img.height * max_w / img.width)), Image.LANCZOS)
out = src.with_suffix(".webp")
if img.mode in ("RGBA", "LA", "PA"):
img.save(out, "WEBP", quality=q, method=6, exact=True)
else:
img.convert("RGB").save(out, "WEBP", quality=q, method=6)
if drop:
src.unlink()
method=6 是压缩最慢但体积最小的方法。一次性脚本无所谓速度。
体积对比
原始 18 张 PNG 46.61 MB
WebP 1.37 MB
节省 97%
注意点
- alpha 通道:保留透明的话用
RGBA → WebP,不要convert("RGB") - 动画:Pillow 不支持 WebP 动画输出(只支持静态)
- 降级:Safari 对早期 WebP 支持差,但目前 Safari 14+ 都 OK
- 质量参数:80 是 sweet spot,60 以下可见噪点
不该用 WebP 的情况
- 图标:PNG-8 更小
- 1px 线条/字体:可能出锯齿
- Logo:SVG 才是正解
评论