40 lines
1.8 KiB
Python
40 lines
1.8 KiB
Python
# FreeType's view of bitmap fonts (run by tools/fixtures/bitmapfonts.py in a nix python with freetype-py): stdin is
|
|
# JSON { fonts: [ { path, chars } ] }; prints JSON [ { glyphs: [ { cp, width, height, left, top, advance, pixels(hex) } ],
|
|
# ascent, descent, family, style, height } ] from FT_LOAD_RENDER | FT_LOAD_TARGET_MONO on the first strike.
|
|
import json, sys
|
|
import freetype
|
|
|
|
req = json.load(sys.stdin)
|
|
out = []
|
|
for f in req["fonts"]:
|
|
face = freetype.Face(f["path"])
|
|
if face.num_fixed_sizes:
|
|
face.select_size(0)
|
|
glyphs = []
|
|
unicode = any(cm.encoding == freetype.FT_ENCODING_UNICODE for cm in face.charmaps)
|
|
if not unicode and face.charmaps:
|
|
face.set_charmap(face.charmaps[0]) # Windows FNT: byte codes (compared for ASCII only)
|
|
for cp in f["chars"]:
|
|
if not unicode and cp >= 128:
|
|
continue
|
|
gi = face.get_char_index(cp)
|
|
if gi == 0:
|
|
continue
|
|
face.load_glyph(gi, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_MONO)
|
|
g = face.glyph
|
|
bm = g.bitmap
|
|
w, h, pitch = bm.width, bm.rows, bm.pitch
|
|
buf = bm.buffer
|
|
px = bytearray(w * h)
|
|
for y in range(h):
|
|
for x in range(w):
|
|
if (buf[y * pitch + x // 8] >> (7 - x % 8)) & 1:
|
|
px[y * w + x] = 255
|
|
glyphs.append({"cp": cp, "width": w, "height": h, "left": g.bitmap_left, "top": g.bitmap_top,
|
|
"advance": g.advance.x >> 6, "pixels": px.hex()})
|
|
m = face.size
|
|
out.append({"unicode": unicode, "glyphs": glyphs, "ascent": m.ascender >> 6, "descent": -(m.descender >> 6), "height": m.height >> 6,
|
|
"family": (face.family_name or b"").decode("latin-1"), "style": (face.style_name or b"").decode("latin-1"),
|
|
"numGlyphs": face.num_glyphs})
|
|
print(json.dumps(out))
|