Изображения

Сгенерировать favicon и иконки сайта

Создает ICO, PNG-иконки и manifest из одного квадратного исходника с прозрачным фоном.

Python Windows macOS Linux Средний
Скачать generate_favicon.py
Описание

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

Скрипт масштабирует исходное изображение в набор размеров для браузеров и мобильных устройств. ICO собирается из нескольких размеров, для иконки на домашнем экране подставляется белый фон. Готовые файлы и site.webmanifest складываются в указанную папку, исходник не меняется.

Запуск

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

python generate_favicon.py --input ./logo.png --out ./public --name "Demo Site"

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

Примеры

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

  • python generate_favicon.py --input ./logo.png --out ./public
  • python generate_favicon.py --input ./logo.png --out ./static --name "Demo" --overwrite
Зависимости

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

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
Исходник

generate_favicon.py

#!/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())

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

CLI 1.0.0

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

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

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

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

Категория

Изображения

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