业务需求:动态资源太大,导致客户端性能较差,高峰时期容易出现卡顿等情况。在此基础上进行资源压缩优化。
使用 Python 压缩一个 .webp 格式的动图,同时保证图片质量与原图高度一致,使用了下方的三方库
- Pillow: 支持处理
.webp图片,可以用来读取和保存 webp 格式的图片。 - imageio: 适合处理动图(包括
.webp格式的动图)。
具体实现
- 读取 webp 动图:使用
imageio读取动图。 - 逐帧压缩图像:对每一帧应用压缩,保证图片效果保持一致。
- 保存动图:使用 Pillow 将每一帧保存为压缩后的
.webp动图。
from PIL import Image
import imageio.v2 as imageio # 使用 imageio.v2 以确保兼容性
import os
# 读取webp动图
def compress_webp_gif(input_path, output_path, quality=85):
# 读取webp动图
gif = imageio.mimread(input_path, format="webp")
# 存储压缩后的帧
compressed_frames = []
for frame in gif:
# 将帧转为PIL图像
img = Image.fromarray(frame)
# 转换为RGB格式 (WebP支持RGB和RGBA)
img = img.convert("RGB")
# 临时保存压缩后的帧
temp_path = "temp_frame.webp"
img.save(temp_path, format=

6039

被折叠的 条评论
为什么被折叠?



