Изображения

Конвертировать изображения в другой формат

Переводит PNG, JPEG, WebP, TIFF и AVIF в выбранный формат и складывает результат в отдельную папку.

Python Windows macOS Linux Новичок
Скачать convert_format.py
Описание

Что делает скрипт

Скрипт принимает файл или каталог, применяет поворот из EXIF и сохраняет копии в нужном формате. Оригиналы не трогаются, существующие файлы в выходной папке пропускаются без флага --overwrite. Для JPEG прозрачность заменяется белым фоном.

Запуск

Быстрый старт

python convert_format.py --input ./photos --out ./converted --format webp

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python convert_format.py --input ./photos --out ./converted --format jpeg --quality 88
  • python convert_format.py --input ./logo.png --out ./out --format avif
  • python convert_format.py --input ./photos --out ./out --format png --recursive
Зависимости

Что понадобится

Python 3.10+ Интерпретатор Python
Windows winget install Python.Python.3.12
macOS brew install python
Linux sudo apt install python3
Pillow Открытие, обработка и сохранение изображений
Windows py -m pip install Pillow
macOS python3 -m pip install Pillow
Linux python3 -m pip install Pillow
pillow-avif-plugin Поддержка AVIF в старых сборках Pillow
Windows py -m pip install pillow-avif-plugin
macOS python3 -m pip install pillow-avif-plugin
Linux python3 -m pip install pillow-avif-plugin
Исходник

convert_format.py

#!/usr/bin/env python3
"""Пакетная конвертация изображений в JPEG, PNG, WebP, TIFF или AVIF."""
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")

Image.init()

SUFFIXES = {
    "jpeg": ".jpg",
    "png": ".png",
    "webp": ".webp",
    "tiff": ".tiff",
    "avif": ".avif",
}
SOURCE_EXTENSIONS = {
    ".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff", ".bmp", ".avif",
}


def collect(source: Path, recursive: bool) -> list[Path]:
    if source.is_file():
        return [source]
    pattern = "**/*" if recursive else "*"
    return sorted(
        path
        for path in source.glob(pattern)
        if path.is_file() and path.suffix.lower() in SOURCE_EXTENSIONS
    )


def flatten(image: Image.Image) -> Image.Image:
    if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info):
        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 save_image(image: Image.Image, target: Path, fmt: str, quality: int) -> None:
    if fmt == "jpeg":
        flatten(image).save(target, format="JPEG", quality=quality, optimize=True, progressive=True)
        return
    if fmt == "png":
        image.save(target, format="PNG", optimize=True)
        return
    if fmt == "webp":
        image.save(target, format="WEBP", quality=quality, method=6)
        return
    if fmt == "tiff":
        if image.mode not in ("RGB", "RGBA", "L"):
            image = image.convert("RGB")
        image.save(target, format="TIFF", compression="tiff_deflate")
        return
    if image.mode not in ("RGB", "RGBA"):
        image = image.convert("RGB")
    image.save(target, format="AVIF", quality=quality)


def print_avif_hint() -> int:
    print("Для AVIF установите pillow-avif-plugin: python3 -m pip install pillow-avif-plugin")
    return 2


def main() -> int:
    parser = argparse.ArgumentParser(description="Конвертировать изображения в другой формат")
    parser.add_argument("--input", type=Path, required=True, help="Файл или папка")
    parser.add_argument("--out", type=Path, required=True, help="Папка для результатов")
    parser.add_argument("--format", choices=sorted(SUFFIXES), default="jpeg")
    parser.add_argument("--quality", type=int, default=90)
    parser.add_argument("--recursive", action="store_true")
    parser.add_argument("--overwrite", action="store_true")
    args = parser.parse_args()

    if not 1 <= args.quality <= 100:
        parser.error("--quality должен быть от 1 до 100")
    source = args.input.expanduser().resolve()
    if not source.exists():
        parser.error(f"Источник не найден: {source}")

    fmt = args.format
    if fmt == "avif":
        try:
            import pillow_avif  # noqa: F401
        except ImportError:
            pass
        if "AVIF" not in Image.SAVE:
            return print_avif_hint()

    out_dir = args.out.expanduser().resolve()
    out_dir.mkdir(parents=True, exist_ok=True)
    files = collect(source, args.recursive)
    if not files:
        print("Изображения не найдены.")
        return 0

    done = skipped = failed = 0
    for path in files:
        target = out_dir / (path.stem + SUFFIXES[fmt])
        if target.exists() and not args.overwrite:
            print(f"Пропуск: {target.name} уже существует")
            skipped += 1
            continue
        try:
            with Image.open(path) as opened:
                image = ImageOps.exif_transpose(opened)
                save_image(image, target, fmt, args.quality)
        except Exception as error:
            print(f"Ошибка {path}: {error}")
            failed += 1
            continue
        done += 1
        print(f"Готово: {path.name} -> {target.name}")
    print(f"Итог: {done} готово, {skipped} пропущено, {failed} ошибок")
    return 1 if failed else 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get images-convert-format
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Изображения

Конвертация, сжатие, водяные знаки, каталоги и пакетная обработка фото.