import os
from PIL import Image
def compress_images_in_folder(folder_path):
# 检查文件夹是否存在
if not os.path.exists(folder_path):
print(f"错误:文件夹 '{folder_path}' 不存在")
return
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# 跳过子文件夹
if os.path.isdir(file_path):
continue
# 检查文件大小是否超过1MB (1MB = 1024 * 1024 字节)
file_size = os.path.getsize(file_path)
if file_size < 1024 * 1024:
continue
# 检查文件是否为图片
if not is_image_file(filename):
continue
# 压缩图片
try:
compress_image(file_path)
print(f"已压缩: {filename}")
except Exception as e:
print(f"压缩失败: {filename}, 错误: {str(e)}")
def is_image_file(filename):
"""检查文件是否为支持的图片格式"""
# 支持的图片格式列表
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.webp']
return any(filename.lower().endswith(ext) for ext in image_extensions)
def compress_image(image_path):
"""压缩单张图片,保持宽高比,宽度为780px"""
# 打开图片
with Image.open(image_path) as img:
# 获取原始尺寸
width, height = img.size
# 计算新尺寸
new_width = 780
new_height = int(height * (new_width / width))
# 调整图片尺寸
resized_img = img.resize((new_width, new_height), Image.LANCZOS)
# 获取图片格式
file_ext = os.path.splitext(image_path)[1].lower()
if file_ext == '.jpg' or file_ext == '.jpeg':
format = 'JPEG'
save_options = {'quality': 85, 'optimize': True}
elif file_ext == '.png':
format = 'PNG'
save_options = {'compress_level': 9}
elif file_ext == '.webp':
format = 'WebP'
save_options = {'quality': 85}
else:
# 默认使用JPEG格式
format = 'JPEG'
save_options = {'quality': 85, 'optimize': True}
# 保存图片(覆盖原文件)
resized_img.save(image_path, format=format, **save_options)
if __name__ == "__main__":
# 设置要处理的文件夹路径,默认为当前目录
folder_to_process = input("请输入要处理的文件夹路径(直接回车使用当前目录):").strip()
if not folder_to_process:
folder_to_process = os.getcwd()
# 执行图片压缩
compress_images_in_folder(folder_to_process)
请确保已安装 Pillow 库(pip install pillow)。
将以上文件保存为app.py,运行python app.py
压缩过程中会覆盖原文件,请提前备份重要图片
使用说明: