from PIL import Image
import glob
import os
source_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 += 1
print(f"图片{filename}转换成功!")
print(f"成功转换{success_count}张图像!")
注:
(1)运行时将 source_folder 和 destination_folder 替换为自己的文件夹路径;
(2)ext 和
new 变量表示源文件的扩展名和目标文件的扩展名。