這個腳本會同時放出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