#!/usr/bin/env python3 import sys import subprocess import os from pathlib import Path exts = {'.jpg', '.jpeg', '.png', '.gif', '.tif', '.tiff', '.webp', '.heic', '.heif', '.bmp'} def process_dir(dirpath, quality, w, h): print(dirpath) outdir = dirpath # outdir = Path(os.path.join("thumbnails", dirpath)) outdir.mkdir(parents=True, exist_ok=True) for entry in sorted(Path(dirpath).iterdir()): if entry.is_dir(): child_dirpath = os.path.join(dirpath, entry.name) process_dir(entry, quality, w, h) if not entry.is_file() or entry.suffix.lower() not in exts: continue out = outdir / entry.name cmd = ["magick", str(entry), "-auto-orient", "-thumbnail", f"{w}x{h}>", "-quality", quality, str(out) + ".jpg"] p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, bufsize=1) # stream stderr lines as they arrive for line in p.stderr: sys.stdout.write(line) p.wait() if p.returncode != 0: print(f"Command failed for {f} with exit {p.returncode}", file=sys.stdout) # The file for magick must be have ending .jpg, therefore create other and then move here os.rename(str(out) + ".jpg", str(out) + ".thumbnail") if __name__ == '__main__': if len(sys.argv) < 2: print("Usage: make_thumbs.py /path/to/folder [max_width] [max_height]", file=sys.stderr) sys.exit(2) dirpath = Path(sys.argv[1]) quality = sys.argv[2] if len(sys.argv) > 2 else "85" w = sys.argv[3] if len(sys.argv) > 3 else "400" h = sys.argv[4] if len(sys.argv) > 4 else "400" process_dir(dirpath, quality, w, h)