76 lines
3.1 KiB
Python
76 lines
3.1 KiB
Python
import os
|
||
from pathlib import Path
|
||
from PIL import Image
|
||
|
||
def convert_images_to_webp_in_out_dir():
|
||
"""
|
||
将脚本所在目录下的所有支持的图片格式转换为 WebP 格式,并输出到 'out' 子目录。
|
||
|
||
功能:
|
||
- 高质量压缩 (quality=85, method=6)。
|
||
- 保留图片透明度。
|
||
- 不删除原始文件。
|
||
- 自动创建 'out' 目录用于存放结果。
|
||
- 自动跳过在 'out' 目录中已存在的同名 WebP 文件。
|
||
"""
|
||
try:
|
||
# 使用 pathlib 获取脚本所在的目录,这是更现代、更健壮的方式
|
||
script_dir = Path(__file__).parent
|
||
output_dir = script_dir / 'out'
|
||
|
||
# 创建输出目录,如果目录已存在则什么也不做
|
||
output_dir.mkdir(exist_ok=True)
|
||
|
||
# 支持转换的图片格式列表
|
||
supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff']
|
||
|
||
print("--- 开始处理图片转换任务 ---")
|
||
print(f"源目录: {script_dir}")
|
||
print(f"输出目录: {output_dir}")
|
||
print("-" * 30)
|
||
|
||
# 遍历目录中的所有文件
|
||
for file_path in script_dir.iterdir():
|
||
# 只处理文件,跳过子目录
|
||
if not file_path.is_file():
|
||
continue
|
||
|
||
# 检查文件扩展名是否在支持的格式列表中 (忽略大小写)
|
||
if file_path.suffix.lower() in supported_formats:
|
||
output_path = output_dir / f"{file_path.stem}.webp"
|
||
|
||
# 如果同名的 webp 文件已存在,则跳过
|
||
if output_path.exists():
|
||
print(f"跳过: {file_path.name} (目标文件已存在)")
|
||
continue
|
||
|
||
try:
|
||
# 打开图片文件
|
||
with Image.open(file_path) as img:
|
||
# Pillow 的 WebP 保存器会自动处理 RGBA (带透明通道) 和 RGB 模式。
|
||
# 对于 GIF 动图,默认只保存第一帧。
|
||
|
||
# 保存为 WebP
|
||
# quality: 质量参数,1-100。85 是在质量和体积之间很好的平衡点。
|
||
# method: 压缩算法,0-6。6 是最慢但压缩效果最好的。
|
||
img.save(output_path, 'webp', quality=85, method=6)
|
||
|
||
original_size_kb = file_path.stat().st_size / 1024
|
||
new_size_kb = output_path.stat().st_size / 1024
|
||
|
||
print(f"成功: {file_path.name} ({original_size_kb:.1f} KB) -> out/{output_path.name} ({new_size_kb:.1f} KB)")
|
||
|
||
except Exception as e:
|
||
print(f"失败: 转换 {file_path.name} 时发生错误: {e}")
|
||
|
||
print("-" * 30)
|
||
print("--- 所有图片处理完成! ---")
|
||
|
||
except NameError:
|
||
print("错误: 此脚本似乎不是作为文件直接运行的。请将其保存为 .py 文件后执行。")
|
||
except Exception as e:
|
||
print(f"发生意外错误: {e}")
|
||
|
||
|
||
if __name__ == '__main__':
|
||
convert_images_to_webp_in_out_dir() |