import os from PIL import Image # 获取当前工作目录,即当前打开的文件夹 source_folder = os.getcwd() # 设置背景颜色和目标文件夹 background_color = (0, 255, 0, 255) destination_folder_name = "out" destination_folder_path = os.path.join(source_folder, destination_folder_name) # 创建目标文件夹(如果不存在) if not os.path.exists(destination_folder_path): os.mkdir(destination_folder_path) # 遍历所有PNG文件并添加背景 for filename in os.listdir(source_folder): if filename.endswith(".png"): # 打开PNG文件 image_path = os.path.join(source_folder, filename) image = Image.open(image_path) # 创建新的背景图像 background = Image.new("RGBA", image.size, background_color) # 将原始图像粘贴到背景图像中 background.paste(image, mask=image.split()[3]) # 保存新的图像 new_filename = os.path.join(destination_folder_path, filename) background.save(new_filename, format="PNG") # 更新目标文件夹的路径 destination_folder = destination_folder_path