|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Optimize images for the Weekly Dev Chat website. |
| 4 | +
|
| 5 | +Converts images to WebP format, resizes to a max width, and reports savings. |
| 6 | +The original file is preserved; the optimized WebP is written alongside it. |
| 7 | +
|
| 8 | +Usage: |
| 9 | + python scripts/optimize_image.py image1.png image2.jpg |
| 10 | + python scripts/optimize_image.py --quality 85 --max-width 1600 image.png |
| 11 | +""" |
| 12 | + |
| 13 | +import argparse |
| 14 | +import sys |
| 15 | + |
| 16 | +if sys.version_info < (3, 14): |
| 17 | + print( |
| 18 | + f"Error: Python 3.14 or later is required (running {sys.version}).", |
| 19 | + file=sys.stderr, |
| 20 | + ) |
| 21 | + sys.exit(1) |
| 22 | + |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +try: |
| 26 | + from PIL import Image, ImageOps |
| 27 | +except ImportError: |
| 28 | + print( |
| 29 | + "Error: Pillow is not installed.\n" |
| 30 | + "Install dev dependencies with:\n" |
| 31 | + " pip install -r requirements-dev.txt\n" |
| 32 | + "Or install Pillow directly:\n" |
| 33 | + " pip install Pillow", |
| 34 | + file=sys.stderr, |
| 35 | + ) |
| 36 | + sys.exit(1) |
| 37 | + |
| 38 | +SUPPORTED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tiff", ".tif"} |
| 39 | + |
| 40 | + |
| 41 | +def _quality_int(value: str) -> int: |
| 42 | + """Argparse type for --quality: integer in range 1–100.""" |
| 43 | + v = int(value) |
| 44 | + if not (1 <= v <= 100): |
| 45 | + raise argparse.ArgumentTypeError(f"quality must be between 1 and 100 (got {v})") |
| 46 | + return v |
| 47 | + |
| 48 | + |
| 49 | +def _positive_int(value: str) -> int: |
| 50 | + """Argparse type for --max-width: integer greater than 0.""" |
| 51 | + v = int(value) |
| 52 | + if v <= 0: |
| 53 | + raise argparse.ArgumentTypeError(f"max-width must be greater than 0 (got {v})") |
| 54 | + return v |
| 55 | + |
| 56 | + |
| 57 | +def optimize_image(input_path: Path, *, quality: int, max_width: int) -> Path | None: |
| 58 | + """Optimize a single image. Returns the output path, or None on error.""" |
| 59 | + if input_path.suffix.lower() not in SUPPORTED_EXTENSIONS: |
| 60 | + print(f" Skipping {input_path.name}: unsupported format") |
| 61 | + return None |
| 62 | + |
| 63 | + try: |
| 64 | + img = Image.open(input_path) |
| 65 | + except Exception as e: |
| 66 | + print(f" Error opening {input_path.name}: {e}", file=sys.stderr) |
| 67 | + return None |
| 68 | + |
| 69 | + # Apply EXIF orientation so JPEGs rotated via metadata are correctly oriented |
| 70 | + img = ImageOps.exif_transpose(img) |
| 71 | + |
| 72 | + # Convert palette/RGBA images appropriately for WebP |
| 73 | + if img.mode in ("P", "PA"): |
| 74 | + img = img.convert("RGBA") |
| 75 | + elif img.mode not in ("RGB", "RGBA"): |
| 76 | + img = img.convert("RGB") |
| 77 | + |
| 78 | + # Resize if wider than max_width, preserving aspect ratio |
| 79 | + if img.width > max_width: |
| 80 | + ratio = max_width / img.width |
| 81 | + new_height = round(img.height * ratio) |
| 82 | + img = img.resize((max_width, new_height), Image.LANCZOS) |
| 83 | + |
| 84 | + output_path = input_path.with_suffix(".webp") |
| 85 | + img.save(output_path, "WEBP", quality=quality) |
| 86 | + |
| 87 | + original_size = input_path.stat().st_size |
| 88 | + optimized_size = output_path.stat().st_size |
| 89 | + change_pct = (optimized_size / original_size - 1) * 100 if original_size > 0 else 0 |
| 90 | + |
| 91 | + print(f" {input_path.name}") |
| 92 | + print(f" {original_size:,} bytes → {optimized_size:,} bytes ({change_pct:+.1f}%)") |
| 93 | + print(f" Saved to {output_path.name} ({img.width}x{img.height})") |
| 94 | + |
| 95 | + return output_path |
| 96 | + |
| 97 | + |
| 98 | +def main() -> None: |
| 99 | + parser = argparse.ArgumentParser( |
| 100 | + description="Optimize images for the Weekly Dev Chat website.", |
| 101 | + ) |
| 102 | + parser.add_argument( |
| 103 | + "images", |
| 104 | + nargs="+", |
| 105 | + type=Path, |
| 106 | + help="One or more image file paths to optimize.", |
| 107 | + ) |
| 108 | + parser.add_argument( |
| 109 | + "--quality", |
| 110 | + type=_quality_int, |
| 111 | + default=80, |
| 112 | + help="WebP quality (1-100, default: 80).", |
| 113 | + ) |
| 114 | + parser.add_argument( |
| 115 | + "--max-width", |
| 116 | + type=_positive_int, |
| 117 | + default=1200, |
| 118 | + help="Max image width in pixels (default: 1200). Images smaller than this are not upscaled.", |
| 119 | + ) |
| 120 | + args = parser.parse_args() |
| 121 | + |
| 122 | + successes = 0 |
| 123 | + failures = 0 |
| 124 | + |
| 125 | + for image_path in args.images: |
| 126 | + if not image_path.is_file(): |
| 127 | + print(f" Warning: {image_path} not found, skipping.", file=sys.stderr) |
| 128 | + failures += 1 |
| 129 | + continue |
| 130 | + |
| 131 | + result = optimize_image(image_path, quality=args.quality, max_width=args.max_width) |
| 132 | + if result: |
| 133 | + successes += 1 |
| 134 | + else: |
| 135 | + failures += 1 |
| 136 | + |
| 137 | + print(f"\nDone: {successes} optimized, {failures} skipped/failed.") |
| 138 | + sys.exit(1 if failures > 0 and successes == 0 else 0) |
| 139 | + |
| 140 | + |
| 141 | +if __name__ == "__main__": |
| 142 | + main() |
0 commit comments