#!/usr/bin/env python3 """Генерация favicon, PNG-иконок и webmanifest из одного изображения.""" from __future__ import annotations import argparse import json import sys from pathlib import Path try: from PIL import Image, ImageOps except ImportError: sys.exit("Нужен Pillow: python3 -m pip install Pillow") PNG_SIZES = { "favicon-16x16.png": 16, "favicon-32x32.png": 32, "favicon-48x48.png": 48, "android-chrome-192x192.png": 192, "android-chrome-512x512.png": 512, } APPLE_SIZE = 180 def main() -> int: parser = argparse.ArgumentParser(description="Сгенерировать favicon и иконки сайта") parser.add_argument("--input", type=Path, required=True, help="Исходный PNG или JPEG") parser.add_argument("--out", type=Path, required=True) parser.add_argument("--name", default="Site") parser.add_argument("--overwrite", action="store_true") args = parser.parse_args() source = args.input.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") out_dir = args.out.expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) targets = list(PNG_SIZES) + ["apple-touch-icon.png", "favicon.ico", "site.webmanifest"] existing = [name for name in targets if (out_dir / name).exists()] if existing and not args.overwrite: print("Файлы уже существуют: " + ", ".join(existing)) print("Добавьте --overwrite, чтобы заменить их.") return 2 try: with Image.open(source) as opened: image = ImageOps.exif_transpose(opened).convert("RGBA") except Exception as error: print(f"Не удалось открыть {source}: {error}") return 1 side = max(image.size) canvas = Image.new("RGBA", (side, side), (0, 0, 0, 0)) canvas.paste(image, ((side - image.width) // 2, (side - image.height) // 2), image) for name, size in PNG_SIZES.items(): icon = canvas.resize((size, size), Image.Resampling.LANCZOS) icon.save(out_dir / name, format="PNG", optimize=True) apple = canvas.resize((APPLE_SIZE, APPLE_SIZE), Image.Resampling.LANCZOS) apple_canvas = Image.new("RGBA", (APPLE_SIZE, APPLE_SIZE), (255, 255, 255, 255)) apple_canvas.alpha_composite(apple) apple_canvas.convert("RGB").save(out_dir / "apple-touch-icon.png", format="PNG", optimize=True) ico_base = canvas.resize((256, 256), Image.Resampling.LANCZOS) ico_base.save( out_dir / "favicon.ico", format="ICO", sizes=[(16, 16), (32, 32), (48, 48)], ) manifest = { "name": args.name, "short_name": args.name[:12], "icons": [ {"src": "android-chrome-192x192.png", "sizes": "192x192", "type": "image/png"}, {"src": "android-chrome-512x512.png", "sizes": "512x512", "type": "image/png"}, ], "theme_color": "#ffffff", "background_color": "#ffffff", "display": "standalone", } (out_dir / "site.webmanifest").write_text( json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"Иконки созданы в {out_dir}") return 0 if __name__ == "__main__": raise SystemExit(main())