使用Python多线程批量压缩图片文件

在现代社会中,图片已经成为人们生活中不可或缺的一部分,在很多应用中,我们需要处理大量的图片文件,并且常常需要将它们进行压缩以减小文件大小,提高加载速度,

如何使用Python的多线程功能来批量压缩图片文件,并通过一个简单的实例代码展示了具体的操作步骤。通过并发处理,可以提高图片压缩的效率,节省时间,在实际项目中,可以根据需要调整线程数量和优化压缩算法,以达到更好的性能和用户体验。

在开始之前,我们需要安装Pillow库,它是Python中处理图片的库;

可以通过以下命令使用pip进行安装:

pip install Pillow

下面是完整的 Python 代码:

import os
from PIL import Image
from concurrent.futures import ThreadPoolExecutor
import threading

# 全局变量和锁用于跟踪处理的图像数量
processed_images_count = 0
processed_images_lock = threading.Lock()

def is_image_file(file):
    try:
        with Image.open(file) as img:
            return img.format in ['JPEG', 'PNG', 'BMP', 'GIF', 'TIFF']
    except IOError as e:
        print(f"无法打开图像文件 {file}: {e}")  # 打印错误信息和文件路径
        return False


def compress_image(input_file):
    global processed_images_count

    print(f"正在处理图像: {input_file}")  # 添加了调试信息

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

            # 保存压缩后的图像
            img.save(input_file, format=file_format, optimize=True)
            print(f"已压缩图像: {input_file}")  # 添加了调试信息

    except Exception as e:  # 捕获所有异常
        print(f"压缩图像时发生错误 {input_file}: {e}")  # 打印错误信息和文件路径

    # 更新已处理图像的计数器
    with processed_images_lock:
        processed_images_count += 1
        print(f"已成功压缩 {processed_images_count} 张图像: {input_file}")

def compress_images_in_folders(thread_count):
    image_files = []

    # 遍历文件夹,找到所有图像文件
    for root, _, files in os.walk(os.getcwd()):
        print(f"正在访问文件夹: {root}")  # 打印正在访问的文件夹
        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 = 32  # 固定线程数量为32
    print(f"使用 {thread_count} 个线程进行图像压缩")
    compress_images_in_folders(thread_count)
  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bingjia_Hu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值