只压缩新增的图片,压缩效果如图:
操作步骤
1. 将脚本保存到任意位置
compress_images.py
python
python
1import os
2import time
3from PIL import Image
4import sys
5
6def compress_image(input_path, quality=75):
7 """
8 压缩图片并直接覆盖原文件
9 :param input_path: 输入图片路径
10 :param quality: 压缩质量 (1-100)
11 """
12 try:
13 # 创建临时备份文件
14 backup_path = f"{input_path}.bak"
15 os.rename(input_path, backup_path)
16
17 with Image.open(backup_path) as img:
18 if img.mode != 'RGB':
19 img = img.convert('RGB')
20 img.save(input_path, quality=quality, optimize=True)
21
22 # 删除备份文件
23 os.remove(backup_path)
24 print(f"成功压缩并替换: {input_path}")
25 except Exception as e:
26 print(f"处理 {input_path} 时出错: {str(e)}")
27
28def process_directory(input_dir, quality=75, timestamp_file='.compress_timestamp'):
29 """
30 处理目录中新增或修改的图片文件并直接覆盖原文件
31 :param input_dir: 输入目录
32 :param quality: 压缩质量 (1-100)
33 :param timestamp_file: 记录上次压缩时间的文件
34 """
35 supported_extensions = ('.jpg', '.jpeg', '.png', '.webp')
36
37 # 获取上次压缩时间
38 last_compress_time = 0
39 if os.path.exists(timestamp_file):
40 with open(timestamp_file, 'r') as f:
41 last_compress_time = float(f.read())
42
43 # 遍历目录处理文件
44 for root, _, files in os.walk(input_dir):
45 for file in files:
46 if file.lower().endswith(supported_extensions):
47 input_path = os.path.join(root, file)
48 file_mtime = os.path.getmtime(input_path)
49 if file_mtime > last_compress_time:
50 compress_image(input_path, quality)
51
52 # 更新压缩时间记录
53 with open(timestamp_file, 'w') as f:
54 f.write(str(time.time()))
55
56if __name__ == "__main__":
57 if len(sys.argv) < 2:
58 print("用法: python compress_images.py <输入目录> [质量(1-100)] [时间戳文件]")
59 sys.exit(1)
60
61 input_dir = sys.argv[1]
62 quality = int(sys.argv[2]) if len(sys.argv) > 2 else 75
63 timestamp_file = sys.argv[3] if len(sys.argv) > 3 else '.compress_timestamp'
64
65 process_directory(input_dir, quality, timestamp_file)
注意:
- 该脚本默认压缩质量为 75,可根据需要自行修改。
- 该脚本默认会在当前目录下创建一个
.compress_timestamp
文件来记录上次压缩时间,可根据需要自行修改。
2. 运行脚本
- 默认压缩
bash
bash
1python compress_images.py content
- 自定义压缩质量
bash
bash
1python compress_images.py content 85
- 自定义时间戳文件
bash
bash
1python compress_images.py content 85 my_timestamp.txt