Вписать фото в квадрат
Добавляет поля нужного цвета и делает квадратное изображение без обрезки важных деталей.
Что делает скрипт
Скрипт масштабирует картинку так, чтобы она целиком поместилась в квадрат заданного размера, а свободное место заполняет выбранным цветом. Прозрачность PNG и WebP сохраняется. Результаты пишутся в отдельную папку, исходные файлы не меняются.
Быстрый старт
python fit_square.py --dir ./photos --out ./square --size 1080
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python fit_square.py --dir ./photos --out ./square --size 1080 --color #f3f4f6python fit_square.py --dir ./products --out ./square --size 2048 --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
fit_square.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 parse_color(value: str) -> tuple[int, int, int]:
text = value.strip().lstrip("#")
if len(text) != 6:
raise argparse.ArgumentTypeError("цвет нужен в формате #rrggbb")
try:
return tuple(int(text[index:index + 2], 16) for index in (0, 2, 4))
except ValueError as error:
raise argparse.ArgumentTypeError(f"неверный цвет: {value}") from error
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="Вписать фото в квадрат")
parser.add_argument("--dir", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--size", type=int, default=1080)
parser.add_argument("--color", type=parse_color, default=(255, 255, 255))
parser.add_argument("--recursive", action="store_true")
parser.add_argument("--overwrite", action="store_true")
args = parser.parse_args()
if args.size < 16:
parser.error("--size должен быть не меньше 16")
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)
if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info):
image = image.convert("RGBA")
elif image.mode != "RGB":
image = image.convert("RGB")
square = ImageOps.pad(
image,
(args.size, args.size),
method=Image.Resampling.LANCZOS,
color=args.color,
centering=(0.5, 0.5),
)
fmt = FORMATS[path.suffix.lower()]
if fmt == "JPEG":
flatten(square).save(
target, format="JPEG", quality=92, optimize=True, progressive=True
)
elif fmt == "PNG":
square.save(target, format="PNG", optimize=True)
elif fmt == "WEBP":
square.save(target, format="WEBP", quality=88, method=6)
else:
if square.mode not in ("RGB", "RGBA", "L"):
square = square.convert("RGB")
square.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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.