Bitmap Font Generator — Java source
Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// bitmap-font-generator — charset parser + BMFont TEXT emitter. Java 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 Java browser story and the island
// owns it anyway — pure charset/font-geometry only.
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Package-private: display snippets keep the repo filename (java.java), which
// need not match the class name.
final class BitmapFont {
/** Max valid Unicode scalar value. */
static final int MAX_CODEPOINT = 0x10ffff;
/** The Java twin of the TS FontError class ('invalid' is the only code). */
static final class FontError extends RuntimeException {
final String code = "invalid";
FontError(String message) { super(message); }
}
// Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
private static final Pattern RE_HEX =
Pattern.compile("^u\\+([0-9a-f]+)(?:-([0-9a-f]+))?$", Pattern.CASE_INSENSITIVE);
// Decimal form: N or N-N.
private static final Pattern RE_DEC = Pattern.compile("^(\\d+)(?:-(\\d+))?$");
private static int[] expand(int lo, int hi) {
int[] out = new int[hi - lo + 1];
for (int i = 0; i < out.length; i++) out[i] = lo + i;
return out;
}
/** 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). */
public static int[] parseCharset(String spec) {
String trimmed = spec.trim();
if (trimmed.isEmpty()) {
throw new FontError("Charset is empty — name a preset or list codepoint ranges.");
}
switch (trimmed.toLowerCase()) {
case "ascii": return expand(32, 126);
case "latin1": {
int[] head = expand(32, 126), tail = expand(160, 255);
int[] out = new int[head.length + tail.length];
System.arraycopy(head, 0, out, 0, head.length);
System.arraycopy(tail, 0, out, head.length, tail.length);
return out;
}
case "digits": return expand(48, 57);
}
TreeSet<Integer> seen = new TreeSet<>();
for (String raw : trimmed.split(",")) {
String token = raw.trim().replaceAll("\\s+", "");
Bounds bounds = parseToken(token);
for (int cp = (int) bounds.lo; cp <= (int) bounds.hi; cp++) seen.add(cp);
}
int[] out = new int[seen.size()];
int i = 0;
for (int cp : seen) out[i++] = cp;
return out;
}
/** Inclusive [lo, hi] codepoint bounds of one comma item. */
private record Bounds(long lo, long hi) {}
/** One comma item → inclusive bounds, or FontError when garbage. The TS
* lib anchors two regexes here; the same two regexes run in this port. */
private static Bounds parseToken(String token) {
Matcher hex = RE_HEX.matcher(token);
Matcher dec = RE_DEC.matcher(token);
if (!hex.matches() && !dec.matches()) {
throw new FontError("\"" + token + "\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.");
}
Matcher m = hex.matches() ? hex : dec;
int radix = hex.matches() ? 16 : 10;
// The regex validated plain digits, so a NumberFormatException here can
// only be an overflow — the TS parseInt's Infinity, i.e. outside Unicode.
long lo = parseLongOrMax(m.group(1), radix);
long hi = m.group(2) != null ? parseLongOrMax(m.group(2), radix) : lo;
if (lo > MAX_CODEPOINT || hi > MAX_CODEPOINT) {
throw new FontError("\"" + token + "\" is outside Unicode (max U+10FFFF).");
}
if (lo > hi) {
throw new FontError("\"" + token + "\" runs backwards — put the smaller codepoint first.");
}
return new Bounds(lo, hi);
}
private static long parseLongOrMax(String digits, int radix) {
try {
return Long.parseLong(digits, radix);
} catch (NumberFormatException overflow) {
return Long.MAX_VALUE;
}
}
/** One char entry in the emitted .fnt (geometry already scaled to pixels). */
record FntChar(int codepoint, int x, int y, int w, int h, int xoffset, int yoffset, int xadvance) {}
/** One kerning pair in the emitted .fnt (pixel amount, may be negative). */
record FntKerning(int first, int second, int amount) {}
/** Mirrors the TS info block: padding is broadcast to all four sides. */
record FntInfo(String face, int size, int padding) {}
/** Mirrors the TS common block. */
record FntCommon(int lineHeight, int base, int scaleW, int scaleH) {}
/** Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png"). */
public static String fntText(FntInfo info, FntCommon common, List<FntChar> chars, List<FntKerning> kernings) {
int p = info.padding();
List<String> lines = new ArrayList<>();
lines.add("info face=\"" + info.face() + "\" size=" + info.size()
+ " bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding="
+ p + "," + p + "," + p + "," + p + " spacing=1,1 outline=0");
lines.add("common lineHeight=" + common.lineHeight() + " base=" + common.base()
+ " scaleW=" + common.scaleW() + " scaleH=" + common.scaleH()
+ " pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0");
lines.add("page id=0 file=\"sheet.png\"");
lines.add("chars count=" + chars.size());
for (FntChar c : chars) {
lines.add("char id=" + c.codepoint() + " x=" + c.x() + " y=" + c.y() + " width=" + c.w()
+ " height=" + c.h() + " xoffset=" + c.xoffset() + " yoffset=" + c.yoffset()
+ " xadvance=" + c.xadvance() + " page=0 chnl=15");
}
lines.add("kernings count=" + kernings.size());
for (FntKerning k : kernings) {
lines.add("kerning first=" + k.first() + " second=" + k.second() + " amount=" + k.amount());
}
return String.join("\n", lines);
}
// Example:
// FntInfo info = new FntInfo("TestFace", 32, 1);
// FntCommon common = new FntCommon(38, 29, 128, 128);
// String fnt = BitmapFont.fntText(info, common, List.of(), List.of());
// System.out.println(fnt);
// // info face="TestFace" size=32 ... padding=1,1,1,1 spacing=1,1 outline=0
// // common lineHeight=38 base=29 scaleW=128 scaleH=128 pages=1 ...
// // page id=0 file="sheet.png"
// // chars count=0
// // kernings count=0
/** Demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts). */
public static void main(String[] args) {
System.out.println(join("ascii", parseCharset("ascii")));
int[] latin1 = parseCharset("latin1");
System.out.printf("latin1 len=%d c0=%d c94=%d c95=%d c190=%d%n",
latin1.length, latin1[0], latin1[94], latin1[95], latin1[190]);
int[] digits = parseCharset("digits");
System.out.printf("digits first=%d last=%d len=%d%n", digits[0], digits[digits.length - 1], digits.length);
System.out.printf("ascii-ws len=%d%n", parseCharset(" ASCII ").length);
System.out.printf("latin1-case c95=%d%n", parseCharset("Latin1")[95]);
System.out.printf("digits-ws len=%d%n", parseCharset("\tDigits\n").length);
int[] decRanges = parseCharset("65-90,97-122");
System.out.printf("dec-ranges first=%d last=%d len=%d%n", decRanges[0], decRanges[decRanges.length - 1], decRanges.length);
printSpec("122,65,97");
printSpec("65-70,68,65");
printSpec("U+41");
printSpec("u+41");
int[] hexRange = parseCharset("U+4E00-9FFF");
System.out.printf("U+4E00-9FFF first=%d last=%d len=%d%n", hexRange[0], hexRange[hexRange.length - 1], hexRange.length);
printSpec("65,U+42,67-68");
printSpec(" 65 - 67 , U+0041 ");
printSpec("0");
printSpec("U+10FFFF");
for (String spec : new String[] {"", " ", "abc", "65-,90", "-5", "65,zz", "U+", "U+ZZ", "zz",
"1114112", "U+110000", "65-2000000", "90-65", "U+9FFF-4E00", "0-0x10FFFF"}) {
try {
printSpec(spec);
System.out.printf("ERR %s : NO-ERROR%n", spec);
} catch (FontError e) {
System.out.printf("ERR %s : %s%n", spec, e.code);
}
}
FntInfo info = new FntInfo("TestFace", 32, 1);
FntCommon common = new FntCommon(38, 29, 128, 128);
List<FntChar> chars = List.of(
new FntChar(65, 0, 0, 34, 36, 0, 0, 36),
new FntChar(66, 36, 0, 32, 36, 1, 2, 35));
List<FntKerning> kernings = List.of(new FntKerning(65, 66, -1));
System.out.println("fntText");
System.out.println(fntText(info, common, chars, kernings));
System.out.println("pad " + fntText(new FntInfo("TestFace", 32, 4), common, chars, kernings).split("\n")[0]);
String[] noKern = fntText(info, common, chars, List.of()).split("\n");
System.out.printf("kern0 %s lines=%d%n", noKern[6], noKern.length);
System.out.printf("zerochars lines=%d%n", fntText(info, common, List.of(), List.of()).split("\n").length);
System.out.println("bigcp " + fntText(info, common,
List.of(new FntChar(19968, 0, 0, 32, 32, 0, 0, 32)), List.of()).split("\n")[4]);
}
private static String join(String label, int[] cps) {
StringBuilder out = new StringBuilder(label + " len=" + cps.length);
for (int cp : cps) out.append(' ').append(cp);
return out.toString();
}
private static void printSpec(String spec) {
int[] cps = parseCharset(spec);
System.out.println(join(spec, cps));
}
}
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 →