Уменьшить изображения по максимальной стороне
Вписывает фото в заданные рамки ширины и высоты, не растягивая и не увеличивая мелкие кадры.
Что делает скрипт
Скрипт сохраняет пропорции и уменьшает только те изображения, которые не помещаются в указанные границы. Поддерживаются JPEG, PNG, WebP и TIFF, формат файла сохраняется. По умолчанию мелкие изображения пропускаются, для увеличения нужен флаг --allow-upscale.
Быстрый старт
python resize_max.py --dir ./photos --out ./resized --max-width 1920 --max-height 1080
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python resize_max.py --dir ./photos --out ./resized --max-width 1600 --max-height 1600python resize_max.py --dir ./photos --out ./resized --max-width 800 --max-height 800 --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
resize_max.py
#!/usr/bin/env python3
"""Уменьшение изображений с сохранением пропорций."""
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",
}
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") 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 main() -> int:
parser = argparse.ArgumentParser(description="Уменьшить изображения по максимальной стороне")
parser.add_argument("--dir", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--max-width", type=int, default=1920)
parser.add_argument("--max-height", type=int, default=1080)
parser.add_argument("--quality", type=int, default=90)
parser.add_argument("--allow-upscale", action="store_true")
parser.add_argument("--recursive", action="store_true")
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args()
if args.max_width < 1 or args.max_height < 1:
parser.error("--max-width и --max-height должны быть больше нуля")
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:
image = ImageOps.exif_transpose(opened)
ratio = min(args.max_width / image.width, args.max_height / image.height)
if ratio >= 1 and not args.allow_upscale:
print(f"Пропуск, размер уже подходит: {path.name}")
skipped += 1
continue
if ratio != 1:
size = (max(1, round(image.width * ratio)), max(1, round(image.height * ratio)))
image = image.resize(size, Image.Resampling.LANCZOS)
fmt = FORMATS[path.suffix.lower()]
if fmt == "JPEG":
flatten(image).save(
target, format="JPEG", quality=args.quality, optimize=True, progressive=True
)
elif fmt == "PNG":
image.save(target, format="PNG", optimize=True)
elif fmt == "WEBP":
image.save(target, format="WEBP", quality=args.quality, 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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.