最新发布 python压缩文件夹下的图片

发布时间: 2025-06-26,浏览量:50
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
压缩过程中会覆盖原文件,请提前备份重要图片



使用说明:


  1. 运行脚本后,会提示你输入要处理的文件夹路径。如果直接回车,将使用当前目录。
  2. 脚本会自动查找文件夹中所有大于 1MB 的图片文件(支持 JPG、PNG、BMP 和 WebP 格式)。
  3. 对于符合条件的图片,脚本会将其宽度调整为 780px,高度按比例自动计算。
  4. 压缩后的图片将覆盖原文件,保持文件名不变。



热门文章 经典语录

热门文章 热门文章

查看更多