forked from mei/webp2gif
34 lines
1.3 KiB
Python
34 lines
1.3 KiB
Python
import os
|
||
from PIL import Image
|
||
|
||
def convert_webp_to_gif(input_folder, output_folder):
|
||
"""
|
||
批量将指定文件夹内的webp图片转换为gif,并保存至另一文件夹。
|
||
|
||
:param input_folder: 存放webp图片的文件夹路径
|
||
:param output_folder: 转换后的gif图片存放的文件夹路径
|
||
"""
|
||
if not os.path.exists(output_folder):
|
||
os.makedirs(output_folder)
|
||
|
||
# 遍历输入文件夹中所有文件
|
||
for filename in os.listdir(input_folder):
|
||
if filename.endswith(".webp"):
|
||
webp_path = os.path.join(input_folder, filename)
|
||
gif_path = os.path.join(output_folder, filename[:-5] + ".gif") # 替换后缀名.webp为.gif
|
||
|
||
try:
|
||
with Image.open(webp_path) as im:
|
||
# 如果是动画WebP,则需要特殊处理每一帧并保存为GIF
|
||
if hasattr(im, 'is_animated') and im.is_animated:
|
||
im.save(gif_path, save_all=True)
|
||
else:
|
||
im.convert('RGB').save(gif_path, 'GIF')
|
||
print(f"{filename} 转换成功")
|
||
except Exception as e:
|
||
print(f"{filename} 转换失败: {e}")
|
||
|
||
# 使用函数
|
||
input_dir = 'input' # 输入WebP文件目录
|
||
output_dir = 'output' # 输出GIF文件目录
|
||
convert_webp_to_gif(input_dir, output_dir) |