Конвертировать изображения в другой формат
Переводит PNG, JPEG, WebP, TIFF и AVIF в выбранный формат и складывает результат в отдельную папку.
Что делает скрипт
Скрипт принимает файл или каталог, применяет поворот из 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 88python convert_format.py --input ./logo.png --out ./out --format avifpython convert_format.py --input ./photos --out ./out --format png --recursive
Что понадобится
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
py -m pip install pillow-avif-plugin
python3 -m pip install pillow-avif-plugin
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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.