#pip install Pillow
from PIL import Image
import os
import shutil
input_folder = ‘D:\Camera’ # 输入文件夹
output_quality = 80 # 输出图片质量
备份目录
backup_folder = input_folder + ‘_bak’
shutil.copytree(input_folder, backup_folder)
遍历输入文件夹及子文件夹
for root, dirs, files in os.walk(input_folder):
for file_name in files:
if file_name.endswith(‘.jpg’) or file_name.endswith(‘.jpeg’) or file_name.endswith(‘.png’):
input_file = os.path.join(root, file_name)
output_file = os.path.join(root, file_name)
# 打开图片并获取宽高
image = Image.open(input_file)
width, height = image.size
print(f'处理图片: {input_file}')
# 判断宽度大于高度且宽度大于1920
if width > height and width > 1920:
# 调整宽度为1920,高度按比例缩放
new_width = 1920
new_height = int(height * new_width / width)
image.thumbnail((new_width, new_height))
print(f'调整宽度为: {new_width}, 高度为: {new_height}')
# 判断高度大于宽度且高度大于1920
elif height > width and height > 1920:
# 调整高度为1920,宽度按比例缩放
new_height = 1920
new_width = int(width * new_height / height)
image.thumbnail((new_width, new_height))
print(f'调整高度为: {new_height}, 宽度为: {new_width}')
# 转换为JPEG格式并保存
image = image.convert('RGB')
image.save(output_file, 'JPEG', quality=output_quality)
print(f'保存图片到: {output_file}')
print('-' * 20)