Skip to content

Instantly share code, notes, and snippets.

@thedillonb
Created February 1, 2014 17:07
Show Gist options
  • Save thedillonb/8755267 to your computer and use it in GitHub Desktop.
Save thedillonb/8755267 to your computer and use it in GitHub Desktop.
Extracts glyphs from a TTF format into multiple PNG files using ImageMagick. Boo
# Usage: ruby extract.rb <TTF> <size: WxH> <output dir>
require 'ttfunk'
file = TTFunk::File.open(ARGV[0])
size = ARGV[1]
output_dir = ARGV[2]
`mkdir #{output_dir}`
cmap = file.cmap
chars = {}
unicode_chars = []
cmap.tables.each do |subtable|
next if !subtable.unicode?
chars = chars.merge( subtable.code_map )
end
chars = chars.keys
puts "\n -- Found #{chars.length} characters in this font \n\n"
chars.each do |t|
`convert -size #{size} -background 'transparent' -fill '#fff' -gravity Center -font #{ARGV[0]} label:\"#{t.chr('UTF-8')}\" ./#{output_dir}/#{t}.png`
end
@CAH-MikeEarley
Copy link

Hey--awesome, glad you did this. I'm getting an error:

Done installing documentation for ttfunk after 1 seconds
1 gem installed
L1:downloads user$ ruby extract.rb ~/downloads/vitalpath2/fonts/vitalpath2.ttf     512x512 ~/downloads/vitalpath2extract/ 

 -- Found 661 characters in this font 

extract.rb:22:in ``': string contains null byte (ArgumentError)
    from extract.rb:22:in `block in <main>'
from extract.rb:21:in `each'
from extract.rb:21:in `<main>'
L1:downloads user$ subl extract.rb
L1:downloads user$ ruby extract.rb ~/downloads/vitalpath2/fonts/vitalpath2.ttf     size: 512x512 ~/downloads/vitalpath2extract/

 -- Found 661 characters in this font 

extract.rb:22:in ``': string contains null byte (ArgumentError)
from extract.rb:22:in `block in <main>'
from extract.rb:21:in `each'
from extract.rb:21:in `<main>'
L1:downloads user $ 

@CAH-MikeEarley
Copy link

OK--so the problem is that the .chr method only plays well with ASCII, and a font over 255 characters causes issues. So you have to do this:
chars = chars.keys
chars.pack("U")
And that will convert the characters to usable values outside of the 255 char range. However, you then have to have FreeType installed for Image Magick, etc. I stopped once I figured out the null point issue, b/c I didn't want to mess around with freetype installation, configuration, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment