# -*- coding:utf-8 -*- # @Author len # @Create 2023/10/25 21:09 from PIL import Image import os # 指定包含PNG文件的文件夹路径 folder_path = ('data/pro') # 遍历文件夹中的每个图像文件 for filename in os.listdir(folder_path): # 构建图像文件的完整路径 file_path = os.path.join(folder_path, filename) # 打开图像文件 image = Image.open(file_path) # 获取图像的宽度和高度 width, height = image.size # 检查高度是否大于200 if height > 200: # 计算新的宽度和高度,保持纵横比 new_height = 200 new_width = int(width * (new_height / height)) # 获取图像的宽度和高度 width, height = image.size # 检查宽度是否大于300 if width > 150: # 计算新的宽度和高度,保持纵横比 new_width = 300 new_height = int(height * (new_width / width)) # 等比例调整图像大小 image.thumbnail((new_width, new_height)) # 保存调整大小后的图像(覆盖原始图像) image.save(file_path) # 关闭图像文件 image.close()