Skip to content

Bitmap Font Generator — Python source

Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

# bitmap-font-generator — charset parser + BMFont TEXT emitter (stdlib only).
# Python port of the pure half of src/lib/bitmap-font.ts: preset names,
# decimal and U+HEX range specs in, sorted codepoints out; BMFont TEXT
# documents out. The rasterizing half (opentype.js) has no Python browser
# story and the island owns it anyway — pure charset/font-geometry only.
from __future__ import annotations

import re
from dataclasses import dataclass
from typing import List, Optional, Tuple

# Max valid Unicode scalar value.
MAX_CODEPOINT = 0x10FFFF

# Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
_RE_HEX = re.compile(r"^u\+([0-9a-f]+)(?:-([0-9a-f]+))?$", re.IGNORECASE)
# Decimal form: N or N-N.
_RE_DEC = re.compile(r"^(\d+)(?:-(\d+))?$")


class FontError(Exception):
    """The Python twin of the TS FontError class ('invalid' is the only code)."""

    def __init__(self, message: str) -> None:
        super().__init__(message)


def _range(lo: int, hi: int) -> List[int]:
    """Inclusive [lo, hi] codepoint range expanded to a sorted list."""
    return list(range(lo, hi + 1))


# Named charsets, as documented in the tool docs.
_PRESETS = {
    "ascii": _range(32, 126),
    "latin1": _range(32, 126) + _range(160, 255),
    "digits": _range(48, 57),
}


def parse_charset(spec: str) -> List[int]:
    """Parse a charset spec into a deduped, sorted codepoint list.

    Grammar (whitespace-tolerant, comma-separated items): `ascii`, `latin1`,
    `digits` presets; or items `A` / `A-B` where each side is decimal (`65`,
    `65-90`) or `U+HEX` (`U+41`, `U+4E00-9FFF`; the range end may drop the
    `U+` prefix when the start carries it).
    """
    trimmed = spec.strip()
    if trimmed == "":
        raise FontError("Charset is empty — name a preset or list codepoint ranges.")
    preset = _PRESETS.get(trimmed.lower())
    if preset:
        return list(preset)

    seen = set()
    for raw in trimmed.split(","):
        token = re.sub(r"\s+", "", raw.strip())
        lo, hi = _parse_token(token)
        seen.update(range(lo, hi + 1))
    return sorted(seen)


def _parse_token(token: str) -> Tuple[int, int]:
    """One comma item → inclusive bounds, or FontError when garbage."""
    match = _RE_HEX.match(token) or _RE_DEC.match(token)
    if match is None:
        raise FontError(f'"{token}" is not a codepoint or range — use 65-90 or U+4E00-9FFF.')
    radix = 16 if _RE_HEX.match(token) else 10
    lo = int(match.group(1), radix)
    hi = int(match.group(2), radix) if match.group(2) is not None else lo
    if lo > MAX_CODEPOINT or hi > MAX_CODEPOINT:
        # Arbitrary-precision ints: huge digit strings land here, like the
        # TS parseInt's Infinity.
        raise FontError(f'"{token}" is outside Unicode (max U+10FFFF).')
    if lo > hi:
        raise FontError(f'"{token}" runs backwards — put the smaller codepoint first.')
    return lo, hi


@dataclass
class FntInfo:
    """Mirrors the TS info block: padding is broadcast to all four sides."""

    face: str
    size: int
    padding: int


@dataclass
class FntCommon:
    """Mirrors the TS common block."""

    line_height: int
    base: int
    scale_w: int
    scale_h: int


@dataclass
class FntChar:
    """One char entry in the emitted .fnt (geometry already scaled to pixels)."""

    codepoint: int
    x: int
    y: int
    w: int
    h: int
    xoffset: int
    yoffset: int
    xadvance: int


@dataclass
class FntKerning:
    """One kerning pair in the emitted .fnt (pixel amount, may be negative)."""

    first: int
    second: int
    amount: int


def fnt_text(info: FntInfo, common: FntCommon, chars: List[FntChar], kernings: List[FntKerning]) -> str:
    """Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png")."""
    p = info.padding
    lines = [
        f'info face="{info.face}" size={info.size} bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1'
        f" padding={p},{p},{p},{p} spacing=1,1 outline=0",
        f"common lineHeight={common.line_height} base={common.base} scaleW={common.scale_w}"
        f" scaleH={common.scale_h} pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0",
        'page id=0 file="sheet.png"',
        f"chars count={len(chars)}",
    ]
    lines += [
        f"char id={c.codepoint} x={c.x} y={c.y} width={c.w} height={c.h}"
        f" xoffset={c.xoffset} yoffset={c.yoffset} xadvance={c.xadvance} page=0 chnl=15"
        for c in chars
    ]
    lines.append(f"kernings count={len(kernings)}")
    lines += [f"kerning first={k.first} second={k.second} amount={k.amount}" for k in kernings]
    return "\n".join(lines)

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 →