|
| 1 | +# /// script |
| 2 | +# requires-python = ">=3.11" |
| 3 | +# dependencies = [ |
| 4 | +# "pillow>=11.0.0", |
| 5 | +# "pillow-heif>=0.22.0", |
| 6 | +# ] |
| 7 | +# /// |
| 8 | + |
| 9 | +"""Convert HEIC and HEIF images to JPEG format.""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import argparse |
| 14 | +from dataclasses import dataclass |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +from PIL import Image |
| 18 | +import pillow_heif |
| 19 | + |
| 20 | +# Register HEIF support with Pillow before opening files. |
| 21 | +pillow_heif.register_heif_opener() |
| 22 | + |
| 23 | +SUPPORTED_EXTENSIONS = {".heic", ".heif"} |
| 24 | + |
| 25 | + |
| 26 | +@dataclass(frozen=True) |
| 27 | +class ConversionResult: |
| 28 | + """Capture the outcome for a single source image.""" |
| 29 | + |
| 30 | + source_path: Path |
| 31 | + output_path: Path |
| 32 | + status: str |
| 33 | + |
| 34 | + |
| 35 | +def is_heif_file(path: Path) -> bool: |
| 36 | + """Return whether the path has a supported HEIF extension.""" |
| 37 | + return path.suffix.lower() in SUPPORTED_EXTENSIONS |
| 38 | + |
| 39 | + |
| 40 | +def build_output_path( |
| 41 | + source_path: Path, input_root: Path, output_dir: Path | None |
| 42 | +) -> Path: |
| 43 | + """Build the destination JPEG path for a source HEIF image.""" |
| 44 | + if output_dir is None: |
| 45 | + return source_path.with_suffix(".jpg") |
| 46 | + |
| 47 | + if input_root.is_file(): |
| 48 | + return output_dir / f"{source_path.stem}.jpg" |
| 49 | + |
| 50 | + relative_path = source_path.relative_to(input_root).with_suffix(".jpg") |
| 51 | + return output_dir / relative_path |
| 52 | + |
| 53 | + |
| 54 | +def save_as_jpeg(source_path: Path, output_path: Path, quality: int) -> None: |
| 55 | + """Open a HEIF image and save it as JPEG.""" |
| 56 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 57 | + |
| 58 | + with Image.open(source_path) as image: |
| 59 | + if image.mode not in ("RGB", "L"): |
| 60 | + image = image.convert("RGB") |
| 61 | + image.save(output_path, "JPEG", quality=quality) |
| 62 | + |
| 63 | + |
| 64 | +def convert_heic_to_jpeg( |
| 65 | + source_path: Path, |
| 66 | + input_root: Path, |
| 67 | + output_dir: Path | None = None, |
| 68 | + quality: int = 90, |
| 69 | + overwrite: bool = False, |
| 70 | +) -> ConversionResult: |
| 71 | + """Convert one HEIF image to JPEG.""" |
| 72 | + output_path = build_output_path(source_path, input_root, output_dir) |
| 73 | + |
| 74 | + if output_path.exists() and not overwrite: |
| 75 | + return ConversionResult( |
| 76 | + source_path=source_path, output_path=output_path, status="skipped" |
| 77 | + ) |
| 78 | + |
| 79 | + save_as_jpeg(source_path, output_path, quality) |
| 80 | + return ConversionResult( |
| 81 | + source_path=source_path, output_path=output_path, status="converted" |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +def gather_source_files(input_path: Path) -> list[Path]: |
| 86 | + """Return all HEIF images under the given file or directory.""" |
| 87 | + if input_path.is_file(): |
| 88 | + if not is_heif_file(input_path): |
| 89 | + raise ValueError(f"Unsupported input file: {input_path}") |
| 90 | + return [input_path] |
| 91 | + |
| 92 | + return sorted( |
| 93 | + path for path in input_path.rglob("*") if path.is_file() and is_heif_file(path) |
| 94 | + ) |
| 95 | + |
| 96 | + |
| 97 | +def parse_args() -> argparse.Namespace: |
| 98 | + """Parse command-line arguments.""" |
| 99 | + parser = argparse.ArgumentParser(description="Convert HEIC or HEIF images to JPEG") |
| 100 | + parser.add_argument("input", type=Path, help="Input HEIC/HEIF file or directory") |
| 101 | + parser.add_argument( |
| 102 | + "-o", |
| 103 | + "--output-dir", |
| 104 | + type=Path, |
| 105 | + default=None, |
| 106 | + help="Optional output directory for JPEG files", |
| 107 | + ) |
| 108 | + parser.add_argument( |
| 109 | + "-q", |
| 110 | + "--quality", |
| 111 | + type=int, |
| 112 | + default=90, |
| 113 | + help="JPEG quality from 1 to 100 (default: 90)", |
| 114 | + ) |
| 115 | + parser.add_argument( |
| 116 | + "--overwrite", |
| 117 | + action="store_true", |
| 118 | + help="Replace existing JPEG files instead of skipping them", |
| 119 | + ) |
| 120 | + return parser.parse_args() |
| 121 | + |
| 122 | + |
| 123 | +def main() -> int: |
| 124 | + """Run the CLI conversion workflow.""" |
| 125 | + args = parse_args() |
| 126 | + |
| 127 | + if not args.input.exists(): |
| 128 | + raise FileNotFoundError(f"Input path does not exist: {args.input}") |
| 129 | + |
| 130 | + if not 1 <= args.quality <= 100: |
| 131 | + raise ValueError("Quality must be between 1 and 100") |
| 132 | + |
| 133 | + source_files = gather_source_files(args.input) |
| 134 | + if not source_files: |
| 135 | + print("No HEIC or HEIF files found.") |
| 136 | + return 0 |
| 137 | + |
| 138 | + converted_count = 0 |
| 139 | + skipped_count = 0 |
| 140 | + |
| 141 | + for source_path in source_files: |
| 142 | + result = convert_heic_to_jpeg( |
| 143 | + source_path=source_path, |
| 144 | + input_root=args.input, |
| 145 | + output_dir=args.output_dir, |
| 146 | + quality=args.quality, |
| 147 | + overwrite=args.overwrite, |
| 148 | + ) |
| 149 | + print(f"{result.status:9} {result.source_path} -> {result.output_path}") |
| 150 | + if result.status == "converted": |
| 151 | + converted_count += 1 |
| 152 | + else: |
| 153 | + skipped_count += 1 |
| 154 | + |
| 155 | + print( |
| 156 | + f"Summary: converted={converted_count} skipped={skipped_count} total={len(source_files)}" |
| 157 | + ) |
| 158 | + return 0 |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + raise SystemExit(main()) |
0 commit comments