这个脚本会同时放出4个guetzli进程来压缩jpg和jpeg图片, guetzli消耗非常大, 请根据你当前机器的内存和cpu配置来调整max_processes的值。
先放出脚本源码
import os import subprocess import shlex def traverse(path='.'): file_paths = [] for root, dirs, files in os.walk(path): for file in files: if file.endswith('.jpeg') or file.endswith('.jpg'): file_paths.append(os.path.join(root, file)) return file_paths def run_guetzli(file_paths, max_processes=4): processes = [] for file_path in file_paths: while len(processes) >= max_processes: processes = [p for p in processes if p.poll() is None] time.sleep(5) # 使用 shlex.quote 对文件路径进行转义 safe_file_path = shlex.quote(file_path) try: p = subprocess.Popen( ['guetzli', '--quality', '100', '--nomemlimit', safe_file_path, safe_file_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) processes.append(p) except FileNotFoundError: print(f"guetzli command not found for file {file_path}") if __name__ == "__main__": import time file_paths = traverse('.') run_guetzli(file_paths)
安装guetzli的方法:
苹果
brew install guetzli
linux
https://github.com/google/guetzli/releases