基于Python的图像批量压缩工具
开发
基于Python的图像批量压缩工具实现方案
随着互联网应用的普及,图像文件的大小直接影响着网站加载速度和用户体验。本文将介绍如何使用Python编写一个简单的图像批量压缩工具,帮助开发者快速压缩文件夹内的所有图片。
一、功能需求
- 支持JPEG和PNG格式图片的批量压缩。
- 保持图片的原始分辨率,但降低文件大小。
- 能自动递归处理子文件夹中的图片文件。
- 支持自定义压缩参数,如压缩质量。
二、技术方案 利用Python的Pillow库加载和保存图片,通过调整压缩质量参数对JPEG进行压缩,对于PNG使用Pillow的优化选项降低文件大小。结合os模块遍历文件夹实现批量处理。
三、实现步骤
步骤1:环境准备
安装Pillow库:
pip install pillow
步骤2:编写图像压缩函数
该函数接受图片路径和输出路径,完成图片压缩后保存。
from PIL import Image
def compress_image(input_path, output_path, quality=70):
"""
压缩图像文件
参数:
- input_path: 输入图片路径
- output_path: 压缩后保存路径
- quality: JPEG压缩质量,范围1-95,默认70
"""
img = Image.open(input_path)
if img.format == 'JPEG':
img.save(output_path, "JPEG", quality=quality, optimize=True)
elif img.format == 'PNG':
img.save(output_path, "PNG", optimize=True)
else:
# 其他格式直接保存,不压缩
img.save(output_path)
步骤3:批量处理图片
遍历目标文件夹及其子目录,对每个支持的文件执行压缩操作。
import os
def batch_compress_images(input_dir, output_dir, quality=70):
"""
批量压缩指定目录下的图片
参数:
- input_dir: 输入文件夹路径
- output_dir: 压缩后保存的文件夹路径
- quality: JPEG压缩质量
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for root, dirs, files in os.walk(input_dir):
# 构造对应的输出路径
relative_path = os.path.relpath(root, input_dir)
target_dir = os.path.join(output_dir, relative_path)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
for file in files:
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
input_file_path = os.path.join(root, file)
output_file_path = os.path.join(target_dir, file)
try:
compress_image(input_file_path, output_file_path, quality)
print(f"压缩成功:{output_file_path}")
except Exception as e:
print(f"压缩失败:{input_file_path},错误:{e}")
步骤4:主函数调用示例
if __name__ == "__main__":
input_directory = "images"
output_directory = "compressed_images"
compress_quality = 75
batch_compress_images(input_directory, output_directory, compress_quality)
四、小结
本文通过Python的Pillow库实现了一个简单且实用的图像批量压缩工具,可快速压缩文件夹内的JPEG和PNG图片,便于在网站、APP中优化图片加载速度。读者可以根据需要进一步扩展,比如增加格式支持或压缩后自动替换原图等功能。
编辑:一起学习网