大白兔联盟

文章搜索
搜索
当前位置:首页 > code宝库 > python code > 文章详情

python对多文件夹图片压缩

大白兔    2023-5-31  183  0评论

import os
import sys
from PIL import Image
from concurrent.futures import ThreadPoolExecutor
import multiprocessing

def is_image_file(file):
    try:
        with Image.open(file) as img:
            return img.format in ['JPEG', 'PNG', 'BMP', 'GIF', 'TIFF']
    except IOError:
        return False

def compress_image(input_file):
    # 打开图像文件
    with Image.open(input_file) as img:
        # 获取图像的格式
        file_format = img.format

        try:
            # 保存压缩后的图像
            img.save(input_file, format=file_format, optimize=True)
        except OSError:
            # 如果遇到缺少 EXIF 信息的情况,重新保存图像
            img.save(input_file, format=file_format, optimize=True, exif=b'')

    print(f"图像已成功压缩: {input_file}")

def compress_images_in_folders(thread_count):
    image_files = []

    # 遍历文件夹,找到所有图像文件
    for root, _, files in os.walk(os.getcwd()):
        for file in files:
            input_file = os.path.join(root, file)

            # 检查文件扩展名
            _, ext = os.path.splitext(input_file)
            if ext.lower() in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff']:
                if is_image_file(input_file):
                    image_files.append(input_file)

    # 使用线程池进行图像压缩
    with ThreadPoolExecutor(max_workers=thread_count) as executor:
        executor.map(compress_image, image_files)

if __name__ == "__main__":
    thread_count = multiprocessing.cpu_count()
    print(f"使用 {thread_count} 个线程进行图像压缩")
    compress_images_in_folders(thread_count)

免责声明

本站提供的一切软件、教程和内容信息仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络收集整理,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑或手机中彻底删除上述内容。如果您喜欢该程序和内容,请支持正版,购买注册,得到更好的正版服务。我们非常重视版权问题,如有侵权请邮件与我们联系处理。敬请谅解!

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论