from PIL import Imageimport globimport ossource_folder = '/path/to/source/folder/' # 源文件夹路径destination_folder = '/path/to/destination/folder/' # 目标文件夹路径ext = "bmp"new = "jpg"# 检查文件扩展名是否包含点号if '.' not in ext.strip():ext = '.' + ext.strip()if '.' not in new.strip():new = '.' + new.strip()# 获取源文件夹中指定扩展名的文件列表files = glob.glob(os.path.join(source_folder, '*' + ext))# 计数器,用于记录成功转换的图像数量success_count = 0# 遍历文件列表,将图像保存到目标文件夹中for f in files:im = Image.open(f)filename = os.path.basename(f) # 提取文件名destination_path = os.path.join(destination_folder, filename.replace(ext, new))im.save(destination_path)success_count += 1print(f"图片{filename}转换成功!")print(f"成功转换{success_count}张图像!")
注:
(1)运行时将 source_folder 和 destination_folder替换为自己的文件夹路径;
(2)ext和
new 变量表示源文件的扩展名和目标文件的扩展名。