#!/usr/bin/env python3 """Применить ориентацию EXIF к пикселям изображения.""" from __future__ import annotations import argparse import sys from pathlib import Path try: from PIL import Image, ImageOps except ImportError: sys.exit("Нужен Pillow: python3 -m pip install Pillow") FORMATS = { ".jpg": "JPEG", ".jpeg": "JPEG", ".png": "PNG", ".webp": "WEBP", ".tif": "TIFF", ".tiff": "TIFF", } ORIENTATION_TAG = 274 def collect(root: Path, recursive: bool) -> list[Path]: pattern = "**/*" if recursive else "*" return sorted( path for path in root.glob(pattern) if path.is_file() and path.suffix.lower() in FORMATS ) def flatten(image: Image.Image) -> Image.Image: if image.mode in ("RGBA", "LA"): rgba = image.convert("RGBA") canvas = Image.new("RGB", rgba.size, (255, 255, 255)) canvas.paste(rgba, mask=rgba.getchannel("A")) return canvas if image.mode not in ("RGB", "L"): return image.convert("RGB") return image def main() -> int: parser = argparse.ArgumentParser(description="Повернуть фото по EXIF") parser.add_argument("--dir", type=Path, required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--recursive", action="store_true") parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() root = args.dir.expanduser().resolve() if not root.is_dir(): parser.error(f"Папка не найдена: {root}") out_dir = args.out.expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) files = collect(root, args.recursive) if not files: print("Изображения не найдены.") return 0 done = skipped = failed = 0 for path in files: target = out_dir / path.name if target.exists() and not args.overwrite: skipped += 1 continue try: with Image.open(path) as opened: orientation = opened.getexif().get(ORIENTATION_TAG, 1) if orientation == 1: print(f"Пропуск, поворот не нужен: {path.name}") skipped += 1 continue image = ImageOps.exif_transpose(opened) fmt = FORMATS[path.suffix.lower()] if fmt == "JPEG": flatten(image).save( target, format="JPEG", quality=95, optimize=True, progressive=True ) elif fmt == "PNG": image.save(target, format="PNG", optimize=True) elif fmt == "WEBP": image.save(target, format="WEBP", quality=92, method=6) else: if image.mode not in ("RGB", "RGBA", "L"): image = image.convert("RGB") image.save(target, format="TIFF", compression="tiff_deflate") except Exception as error: print(f"Ошибка {path}: {error}") failed += 1 continue done += 1 print(f"Повернуто: {path.name}") print(f"Итог: {done} повернуто, {skipped} пропущено, {failed} ошибок") return 1 if failed else 0 if __name__ == "__main__": raise SystemExit(main())