App Icon Generator — Python source
Turn one image into the full web app icon set — favicon, apple-touch-icon and manifest sizes as crisp PNGs. Letterboxed contain-fit, optional white background — runs entirely in your browser.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""app-icon-generator — contain-fit, centered export geometry for the
16/32/180/192/512 web icon set.
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `app-icon-generator` tool, ported from
src/tools/AppIconGenerator.tsx.
The island's interactive half — createImageBitmap decode, canvas drawImage,
canvas.toBlob PNG encode — is browser-bound and stays there; this module ports
the deterministic geometry that decides where the source image lands on every
square canvas. One subtlety: Python's round() is banker's rounding
(round(2.5) == 2), so the half-up helper below is what reproduces JS
Math.round on the exact .5 letterbox offsets an odd fit can produce.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import List, Sequence
#: The standard size set every web app is asked for (the island's SIZES).
DEFAULT_SIZES: Sequence[int] = (16, 32, 180, 192, 512)
@dataclass(frozen=True)
class IconRect:
"""One export target: the square canvas edge and the centered contain-fit
rect the source image is drawn into."""
size: int # canvas edge (px × px) this rect was fitted into
x: int # top-left offset: centers the fitted image
y: int
w: int # fitted image size, at least 1×1
h: int
def _round_half_up(value: float) -> int:
"""JS ``Math.round`` for the non-negative values this geometry produces.
Every input is positive (the fitted rect never leaves the canvas), so
``floor(v + 0.5)`` is exact half-up rounding — built-in ``round()`` would
drift to the even neighbour on the exact ``.5`` centered offsets.
"""
return math.floor(value + 0.5)
def icon_set_plan(
src_w: int, src_h: int, sizes: Sequence[int] = DEFAULT_SIZES
) -> List[IconRect]:
"""The deterministic half of the tool: per export size, the contain-fit
rect (scale = min(px/w, px/h), clamped to >= 1) plus the centered draw
offset — the geometry the island feeds ``ctx.drawImage`` before
``canvas.toBlob`` PNG-encodes each square. Bitmap decode and PNG encode
stay with the host.
"""
plan: List[IconRect] = []
for px in sizes:
scale = min(px / src_w, px / src_h)
w = max(1, _round_half_up(src_w * scale))
h = max(1, _round_half_up(src_h * scale))
plan.append(
IconRect(
size=px,
x=_round_half_up((px - w) / 2), # letterbox on transparency
y=_round_half_up((px - h) / 2),
w=w,
h=h,
)
)
return plan
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →