使用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)

相关推荐

  1. 使用Python线批量压缩图片文件

    2024-06-14 00:26:06       7 阅读
  2. Python----线使用

    2024-06-14 00:26:06       8 阅读
  3. python 线处理图片

    2024-06-14 00:26:06       13 阅读
  4. Python线线使用

    2024-06-14 00:26:06       40 阅读
  5. python线使用

    2024-06-14 00:26:06       27 阅读
  6. Python线使用实践

    2024-06-14 00:26:06       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-14 00:26:06       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-14 00:26:06       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-14 00:26:06       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-14 00:26:06       20 阅读

热门阅读

  1. PTA:7-186 水仙花数

    2024-06-14 00:26:06       8 阅读
  2. 6-11 函数题:某范围中的最小值

    2024-06-14 00:26:06       8 阅读
  3. SIM卡 移动、联通、电信对比

    2024-06-14 00:26:06       11 阅读
  4. 【ZZULIOJ】1104: 求因子和(函数专题)

    2024-06-14 00:26:06       7 阅读
  5. QT QByteArray 的用法

    2024-06-14 00:26:06       10 阅读
  6. Dijkstra算法的原理

    2024-06-14 00:26:06       6 阅读
  7. CompletableFuture 异常捕获方式

    2024-06-14 00:26:06       10 阅读
  8. react路由的使用

    2024-06-14 00:26:06       7 阅读
  9. 【BeX5】知识中心

    2024-06-14 00:26:06       7 阅读