Created
March 23, 2020 03:28
-
-
Save nuta/aa4723fb272d346ec1119bd40978f9a1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import argparse | |
| import string | |
| def parse(bdf): | |
| font = { "glyphs": {} } | |
| name = None | |
| glyph = None | |
| lines = list(reversed(bdf.splitlines())) | |
| while len(lines) > 0: | |
| line = lines.pop() | |
| c = line.split(" ") | |
| if len(c) == 0: | |
| continue | |
| if c[0] == "STARTCHAR": | |
| glyph = {} | |
| name = c[1] | |
| elif name is None: | |
| continue | |
| elif c[0] == "ENDCHAR": | |
| font["glyphs"][glyph["ascii"]] = glyph | |
| name = None | |
| glyph = None | |
| elif c[0] == "ENCODING": | |
| glyph["encoding"] = c[1] | |
| # Adobe Standard Encoding is (nearly) identical with ASCII. | |
| glyph["ascii"] = chr(int(c[1])) | |
| elif c[0] == "BBX": | |
| glyph["bbx"] = { | |
| "width": int(c[1]), | |
| "height": int(c[2]), | |
| "off0x": int(c[3]), | |
| "off0y": int(c[4]), | |
| } | |
| elif c[0] == "BITMAP": | |
| bitmap = bytes() | |
| for _ in range(0, glyph["bbx"]["height"]): | |
| bitmap += bytes([int(lines.pop(), 16)]) | |
| glyph["bitmap"] = bitmap | |
| if glyph: | |
| font["glyphs"][glyph["ascii"]] = glyph | |
| return font | |
| def preview(font, glyph): | |
| g = font["glyphs"][glyph] | |
| if not g: | |
| print(f"'{glyph}' not found in the font file") | |
| print(f"Glyph: {glyph}") | |
| print(f"Encoding: {g['encoding']}") | |
| for line in g["bitmap"]: | |
| for i in range(0, 8): | |
| bit = (line >> (7 - i)) & 1 == 1 | |
| if bit: | |
| print("#", end="") # black square | |
| else: | |
| print("_", end="") | |
| print("") | |
| def main(): | |
| parser = argparse.ArgumentParser(description="The BDF font file converter.") | |
| parser.add_argument("--preview", metavar="ASCII") | |
| parser.add_argument("--convert", metavar="OUTFILE") | |
| parser.add_argument("bdf_file") | |
| args = parser.parse_args() | |
| font = parse(open(args.bdf_file).read()) | |
| if args.preview: | |
| preview(font, args.preview) | |
| if args.convert: | |
| bin_font = convert(font) | |
| with open(args.convert, "wb") as f: | |
| f.write(bin_font) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment