南充网站建设略奥科技,整形网站源码,搭建网站需要什么技术,品牌建设汇报在现代社会中#xff0c;图片已经成为人们生活中不可或缺的一部分#xff0c;在很多应用中#xff0c;我们需要处理大量的图片文件#xff0c;并且常常需要将它们进行压缩以减小文件大小#xff0c;提高加载速度#xff0c;
如何使用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 Falsedef compress_image(input_file):global processed_images_countprint(f正在处理图像: {input_file}) # 添加了调试信息try:# 打开图像文件with Image.open(input_file) as img:# 获取图像的格式file_format img.format# 保存压缩后的图像img.save(input_file, formatfile_format, optimizeTrue)print(f已压缩图像: {input_file}) # 添加了调试信息except Exception as e: # 捕获所有异常print(f压缩图像时发生错误 {input_file}: {e}) # 打印错误信息和文件路径# 更新已处理图像的计数器with processed_images_lock:processed_images_count 1print(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_workersthread_count) as executor:executor.map(compress_image, image_files)if __name__ __main__:thread_count 32 # 固定线程数量为32print(f使用 {thread_count} 个线程进行图像压缩)compress_images_in_folders(thread_count)