# -*- coding:utf-8 -*- # @Author len # @Create 2023/10/25 21:07 from PIL import Image import os # 设置要调整大小的目标尺寸 target_size = (800, 480) # target_size = (480, 320) # target_size = (480, 480) # 指定包含背景图像的文件夹路径 folder_path = r"F:\img" # 遍历文件夹中的每个图像文件 for filename in os.listdir(folder_path): # 构建图像文件的完整路径 file_path = os.path.join(folder_path, filename) # 打开图像文件 with Image.open(file_path) as image: # 调整图像大小 resized_image = image.resize(target_size) # 检查是否有Alpha通道 if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info): # 删除alpha通道 alpha = resized_image.split()[-1] background = Image.new("RGB", resized_image.size, (255, 255, 255)) background.paste(resized_image, mask=alpha) resized_image = background # 打印文件路径 print(file_path) # 保存调整大小后的图像 resized_image.save(file_path) # 关闭图像文件不再需要,因为我们使用了上下文管理器'with'