Python 批量图片格式转换:jpg/png/webp 互转教程
用 Python Pillow 批量把目录里的 jpg、png、webp 图片互相转换,支持递归遍历、保留原图、统一命名,给出完整可运行代码和注意事项。
场景痛点
做网站、发公众号、传小程序时,经常要把一堆 jpg 转成 png 透明图,或者把 png 压缩成 webp。用在线工具一张一张传,几十上百张图要折腾半天,还容易传错、压坏。用 Python 写个脚本,指定输入目录和目标格式,一键全部转完,原图保留在原地,输出到新文件夹,稳定可重复。
用到的库
pip install Pillow
完整代码
import os
from PIL import Image
# 支持的输入扩展名
SRC_EXTS = (".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff")
# Pillow 保存格式映射:目标扩展名 -> 保存格式名
FORMAT_MAP = {
".jpg": "JPEG",
".jpeg": "JPEG",
".png": "PNG",
".webp": "WEBP",
}
def convert_one(src_path, dst_path, target_ext, quality=95):
"""把单张图片转成 target_ext 指定的格式"""
img = Image.open(src_path)
# JPEG 不支持透明通道,转换时统一转成 RGB,否则会报错
if target_ext in (".jpg", ".jpeg") and img.mode != "RGB":
img = img.convert("RGB")
save_format = FORMAT_MAP[target_ext]
if save_format == "JPEG":
img.save(dst_path, save_format, quality=quality, optimize=True)
elif save_format == "WEBP":
img.save(dst_path, save_format, quality=quality)
else:
img.save(dst_path, save_format)
print(f"已转换:{src_path} -> {dst_path}")
def batch_convert(src_dir, dst_dir, target_ext=".webp"):
"""遍历 src_dir 下所有图片,批量转换到 dst_dir"""
if target_ext not in FORMAT_MAP:
raise ValueError(f"暂不支持目标格式:{target_ext}")
os.makedirs(dst_dir, exist_ok=True)
for root, _, files in os.walk(src_dir):
for name in files:
if not name.lower().endswith(SRC_EXTS):
continue
src_path = os.path.join(root, name)
# 替换扩展名,保留相对目录结构
rel = os.path.relpath(src_path, src_dir)
new_name = os.path.splitext(rel)[0] + target_ext
dst_path = os.path.join(dst_dir, new_name)
os.makedirs(os.path.dirname(dst_path), exist_ok=True)
try:
convert_one(src_path, dst_path, target_ext)
except Exception as e:
print(f"失败:{src_path},原因:{e}")
def main():
src_dir = "./photos" # 原始图片目录,按实际改
dst_dir = "./photos_webp" # 转换后输出目录
batch_convert(src_dir, dst_dir, target_ext=".webp")
if __name__ == "__main__":
main()
代码讲解
Image.open打开图片,Pillow 会自动识别格式,不需要手动判断。FORMAT_MAP把扩展名映射成 Pillow 的保存格式名,比如.webp对应WEBP。- 转 JPEG 时必须
convert("RGB"),因为 PNG 带透明通道 RGBA,直接存 JPEG 会报 "cannot write mode RGBA as JPEG"。 quality=95控制 JPEG/WEBP 压缩质量,数值越大越清晰、文件越大,常用 80-95。os.walk递归遍历子目录,os.path.relpath保留原来的文件夹层级,转换后目录结构不变。- 单张失败不中断整个批处理,try/except 包住继续跑下一张。
运行结果
把要转的图片放进 ./photos 目录,运行脚本后会在 ./photos_webp 下生成同结构的图片,扩展名统一变成目标格式。控制台逐行打印每张转换结果,失败的图片单独列出原因。
注意事项
- WebP 格式需要 Pillow 安装时带 libwebp 支持,新版 Pillow(>=9.0)默认支持;如果 save WEBP 报错,升级 Pillow:
pip install -U Pillow。 - 原图不会被修改,脚本只读不写原目录,可以放心跑。
- 文件名带中文、空格在大多数系统没问题,但建议输出目录用英文路径,避免老版本 Windows 控制台编码问题。
- 转换上百张大图时一次性全部打开会占内存,脚本是逐张打开逐张关闭,内存占用可控。

更新时间:2026-09-14 20:44:10
上一篇:Python 批量给图片加水印:文字水印和图片水印两种方案