import Image
import ImageFont
import ImageDraw

def bounds(im):
    s = [(x,y) for x in range(im.size[0]) for y in range(im.size[1]) if im.getpixel((x,y))]
    xs = [x for (x,y) in s]
    ys = [y for (x,y) in s]
    return (min(xs), min(ys), max(xs) + 1, max(ys) + 1)

font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf", 15);
im = Image.new("L", (16,16*96))
for i in range(96):
    if 0 < i:
        ch = chr(ord(" ") + i)
        patch = Image.new("L", (64,16))
        draw = ImageDraw.Draw(patch)
        draw.text((16, -2), ch, font=font, fill=255)
        (xmin,_,xmax,_) = bounds(patch)
        patch = patch.crop((xmin,0,xmax,16))
        im.paste(patch, (8 - patch.size[0] / 2, i * 16))

# im = im.resize((im.size[0] * 2, im.size[1]), Image.BICUBIC)
im.convert('P', palette=Image.ADAPTIVE, colors=4).convert("RGB")
im.save("font16.png")
