[Python] 纯文本查看 复制代码 import os
from PIL import Image
import imageio
def convert_webp_to_gif():
"""
将当前文件夹中的 WebP 文件批量转换为 GIF 文件,并将结果保存在当前文件夹。
"""
current_folder = os.getcwd() # 获取当前文件夹路径
for filename in os.listdir(current_folder):
if filename.lower().endswith('.webp'):
webp_path = os.path.join(current_folder, filename)
gif_path = os.path.join(current_folder, f"{os.path.splitext(filename)[0]}.gif")
try:
# 打开 WebP 图片
image = Image.open(webp_path)
# 检测是否为动态 WebP(多帧)
if getattr(image, "is_animated", False):
frames = []
for frame in range(image.n_frames):
image.seek(frame)
frames.append(image.copy())
# 保存为动态 GIF
frames[0].save(
gif_path,
save_all=True,
append_images=frames[1:],
loop=0,
duration=image.info.get("duration", 100),
)
else:
# 保存为静态 GIF
image.save(gif_path, "GIF")
print(f"成功转换: {filename} -> {gif_path}")
except Exception as e:
print(f"转换失败: {filename}, 错误信息: {e}")
# 调用转换函数
convert_webp_to_gif()
有没有图片试一下需要安装库[Python] 纯文本查看 复制代码 pip install pillow imageio
|