Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump characters (glyphs) from TrueType font (TTF) into bitmaps

I have a custom TrueType font (TTF) that consists of a bunch of icons, which I'd like to render as individual bitmaps (GIF, PNG, whatever) for use on the Web. You'd think this is a simple task, but apparently not? There is a huge slew of TTF-related software here:

http://cg.scs.carleton.ca/~luc/ttsoftware.html

But it's all varying levels of "not quite what I want", broken links and/or hard to impossible to compile on a modern Ubuntu box -- eg. dumpglyphs (C++) and ttfgif (C) both fail to compile due to obscure missing dependencies. Any ideas?

like image 928
lambshaanxy Avatar asked Apr 20 '10 02:04

lambshaanxy


2 Answers

Try PIL's ImageDraw and ImageFont module

Code would be something like this

import Image, ImageFont, ImageDraw

im = Image.new("RGB", (800, 600))

draw = ImageDraw.Draw(im)

# use a truetype font
font = ImageFont.truetype("path/to/font/Arial.ttf", 30)

draw.text((0, 0), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", font=font)

# remove unneccessory whitespaces if needed
im=im.crop(im.getbbox())

# write into file
im.save("img.png")
like image 72
YOU Avatar answered Sep 28 '22 05:09

YOU


Here's a working implementation of S.Mark's answer that dumps out chars 'a' to 'z' in black into correctly-sized PNGs:

import Image, ImageFont, ImageDraw

# use a truetype font
font = ImageFont.truetype("font.ttf", 16)
im = Image.new("RGBA", (16, 16))
draw = ImageDraw.Draw(im)

for code in range(ord('a'), ord('z') + 1):
  w, h = draw.textsize(chr(code), font=font)
  im = Image.new("RGBA", (w, h))
  draw = ImageDraw.Draw(im)
  draw.text((-2, 0), chr(code), font=font, fill="#000000")
  im.save(chr(code) + ".png")
like image 26
lambshaanxy Avatar answered Sep 28 '22 03:09

lambshaanxy