Skip to content

Instantly share code, notes, and snippets.

@muhuk
Created September 30, 2014 13:36
Show Gist options
  • Save muhuk/3163863a26a499efb5a1 to your computer and use it in GitHub Desktop.
Save muhuk/3163863a26a499efb5a1 to your computer and use it in GitHub Desktop.
Converts TTF fonts to a PNG file recognized by Love2D game engine.
#!/usr/bin/env python
import sys
from PIL import Image, ImageChops, ImageDraw, ImageFont
BACKGROUND_COLOR = (0, 0, 0, 0)
FONT_COLOR = (255, 255, 255, 255)
MARKER_COLOR = (255, 255, 0, 255)
def create_bitmap_font(font, glyphs, margin=2):
glyphs_width, letter_height = font.getsize(glyphs)
image_width = glyphs_width + (len(glyphs) + 1) * margin
img_main = Image.new('RGBA', (image_width, letter_height), BACKGROUND_COLOR)
ctx_main = ImageDraw.Draw(img_main)
img_glyphs = Image.new('1', (image_width, letter_height), 0)
ctx_glyphs = ImageDraw.Draw(img_glyphs)
left = 0
for letter in glyphs:
letter_width, letter_height = font.getsize(letter)
ctx_main.rectangle((left, 0, left + margin - 1, letter_height), MARKER_COLOR)
left += margin
ctx_glyphs.text((left, 0), letter, font=font, fill=255)
left += letter_width
ctx_main.rectangle((image_width - margin, 0, image_width, letter_height), MARKER_COLOR)
del ctx_main, ctx_glyphs
for y in range(letter_height):
for x in range(image_width):
if img_glyphs.getpixel((x, y)):
img_main.putpixel((x, y), FONT_COLOR)
return img_main
def main():
glyphs = ''.join(map(chr, range(32, 127) + range(160, 256)))
font_path = sys.argv[1]
output_path = sys.argv[2]
font_size = 8
font = ImageFont.truetype(font_path, font_size)
create_bitmap_font(font, glyphs).save(output_path, 'PNG', optimize=True)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment