Повернуть фото по EXIF
Физически применяет ориентацию из EXIF, чтобы кадры не открывались боком в старых программах.
Что делает скрипт
Скрипт читает тег Orientation, поворачивает или отражает пиксели и сохраняет исправленную копию. Файлы без поворота пропускаются, поэтому папка не заполняется лишними дублями. Метаданные камеры в копию не переносятся, оригиналы остаются на месте, результаты попадают в отдельный каталог.
Быстрый старт
python fix_exif_orientation.py --dir ./photos --out ./fixed
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python fix_exif_orientation.py --dir ./photos --out ./fixedpython fix_exif_orientation.py --dir ./photos --out ./fixed --recursive --overwrite
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install Pillow
python3 -m pip install Pillow
python3 -m pip install Pillow
fix_exif_orientation.py
#!/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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.