Skip to content

Instantly share code, notes, and snippets.

@passiomatic
Created August 6, 2017 15:28
Show Gist options
  • Save passiomatic/325ccd8b91ef1f89310faf036eb21580 to your computer and use it in GitHub Desktop.
Save passiomatic/325ccd8b91ef1f89310faf036eb21580 to your computer and use it in GitHub Desktop.
Convert a Bitfontmaker JSON into PNG
# -*- coding: utf-8 -*-
# Convert a Bitfontmaker JSON into PNG (requires Pillow library)
#
# See gallery:
# http://www.pentacom.jp/pentacom/bitfontmaker2/gallery/
#
# Usage:
# python bitfont.py font.json font.png
import sys
import json
from PIL import Image
# Transparent background
BACKGROUND_COLOR = 1, 1, 1, 1
# In order to WebGL friendly the final spritesheet must be a power of two
SIZE = 256, 512
# Render each glyph at ideal size (px)
GLYPH_WIDTH = 16
# Added some padding -- final size should be
# a power of two, so everything align nicely
CELL_SIZE = GLYPH_WIDTH
# All ASCII characters we need
CHARACTERS = range(ord(' '), ord('z') + 1)
BITMASKS = [2**v for v in range(16)]
def draw_glyph(img, position, values):
x, y = position
for offset_y, value in enumerate(values):
if value == 0:
continue # Skip row
for offset_x, bit in enumerate(BITMASKS):
if value & bit:
img.putpixel((x * CELL_SIZE + offset_x, y * CELL_SIZE + offset_y), (0, 0, 0))
def main(args):
_, input_path, output_path = args[0], args[1], args[2]
img = Image.new('RGBA', SIZE, color=BACKGROUND_COLOR)
with open(input_path) as f:
data = cleanup(json.load(f, encoding="utf-8"))
for index, value in enumerate(CHARACTERS):
try:
glyph = data[str(value)]
except KeyError:
continue
col = index % (SIZE[0] / CELL_SIZE)
row = index // (SIZE[0] / CELL_SIZE)
draw_glyph(img, (col, row), glyph)
img.save(output_path, 'PNG')
unwanted = [
"name",
"copy",
"letterspace",
"basefont_size",
"basefont_left",
"basefont_top",
"basefont",
"basefont2"
]
def cleanup(data):
for key in unwanted:
del data[key]
return data
if __name__ == '__main__':
if len(sys.argv) < 3:
print "Not enough arguments given."
else:
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment