你有没有遇到过这种情况:网站只支持上传JPG图片,但你手里全是PNG格式。一张张打开,另存为,选格式,保存……重复几十遍。截图默认存为PNG,想转成JPG省空间,结果一张张改到手酸。设计稿导出全是WEBP,客户非要JPG。
我让AI写了25行代码,做了一个事:批量转换图片格式,PNG↔JPG一键互转,WEBP、BMP随便转。
原来:打开图片 → 另存为 → 选格式 → 保存 → 下一张 → 重复50遍现在:运行脚本 → 输入文件夹路径 → 选目标格式 → 几秒钟搞定
我是怎么让AI写这段代码的
提示词直接贴出来:
text
写一个Python脚本,实现以下功能:
1. 用户输入一个文件夹路径
2. 遍历文件夹里所有图片(jpg、png、webp、bmp)
3. 用户选择目标格式(JPEG/PNG/WEBP/BMP)
4. 批量转换并保存到新文件夹
5. PNG转JPG时自动处理透明背景(变白底)
6. 使用Pillow库
完整代码
python
import osfrom PIL import Imagedef convert_images(folder_path, target_format='JPEG', output_folder='转换后'): """ 批量转换图片格式 folder_path: 图片文件夹路径 target_format: 目标格式(JPEG/PNG/WEBP/BMP) output_folder: 输出文件夹 """ # 支持的输入格式 input_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.webp', '.gif') # 获取所有图片 images = [f for f in os.listdir(folder_path) if f.lower().endswith(input_extensions)] if not images: print("未找到图片文件") return print(f"找到 {len(images)} 张图片") print(f"目标格式: {target_format}") # 创建输出文件夹 output_path = os.path.join(folder_path, output_folder) os.makedirs(output_path, exist_ok=True) # 格式转扩展名 format_map = { 'JPEG': '.jpg', 'PNG': '.png', 'WEBP': '.webp', 'BMP': '.bmp' } ext = format_map.get(target_format, '.jpg') success_count = 0 for img_file in images: input_file = os.path.join(folder_path, img_file) name = os.path.splitext(img_file)[0] output_file = os.path.join(output_path, f"{name}{ext}") try: img = Image.open(input_file) # PNG/透明图转JPG:先转RGB(白色背景) if target_format == 'JPEG' and img.mode in ('RGBA', 'LA', 'P'): rgb_img = Image.new('RGB', img.size, (255, 255, 255)) if img.mode == 'P': img = img.convert('RGBA') if img.mode == 'RGBA': rgb_img.paste(img, mask=img.split()[-1]) else: rgb_img.paste(img) img = rgb_img elif target_format == 'JPEG' and img.mode != 'RGB': img = img.convert('RGB') # 保存 img.save(output_file, format=target_format, quality=95) success_count += 1 print(f" ✅ {img_file} -> {name}{ext}") except Exception as e: print(f" ❌ {img_file} 失败: {str(e)}") print(f"\n✅ 完成!成功转换 {success_count} 张图片") print(f"保存在: {output_path}")if __name__ == "__main__": print("=" * 50) print("🖼️ 批量转换图片格式") print("=" * 50) path = input("请输入图片文件夹路径: ").strip() if path.startswith('"') and path.endswith('"'): path = path[1:-1] path = path.replace('\\', '/') if not os.path.exists(path): print("❌ 路径不存在") input("按回车键退出...") exit() print("\n支持的格式: JPEG, PNG, WEBP, BMP") target = input("请输入目标格式(默认JPEG): ").strip().upper() if not target: target = 'JPEG' if target not in ['JPEG', 'PNG', 'WEBP', 'BMP']: print("❌ 不支持的格式") input("按回车键退出...") exit() convert_images(path, target) input("\n按回车键退出...")
安装依赖
bash
pip install Pillow
使用步骤
安装依赖:pip install Pillow
把代码保存为 convert_image.py
把所有要转换的图片放在同一个文件夹
运行 python convert_image.py,输入文件夹路径
输入目标格式(JPEG/PNG/WEBP/BMP)
打开同目录下的「转换后」文件夹
踩坑记录
坑1: PNG透明背景转JPG后背景变黑。解决方案:先创建白色背景画布,把PNG贴上去,再保存为JPG。
坑2: 有些图片模式不支持直接转换。解决方案:自动检测并转换模式(RGBA→RGB)。
坑3: WEBP格式在某些软件打不开。解决方案:转换时确保格式参数正确。
还能怎么玩
批量重命名 + 转换格式(一次完成)
转换后自动压缩(搭配第2个工具)
指定图片尺寸(转换的同时统一大小)