Extracting hte font name from a TrueType font file
Aaron "Castironpi" Brady
castironpi at gmail.com
Fri Sep 19 00:38:09 EDT 2008
On Sep 18, 7:48 pm, Steve Holden <st... at holdenweb.com> wrote:
> Fredrik Lundh wrote:
> > Steve Holden wrote:
>
> >> Does anyone have a Python recipe for this?
>
> >>>> from PIL import ImageFont
> >>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1)
> >>>> f.font.family
> > 'Verdana'
> >>>> f.font.style
> > 'Italic'
>
> Thanks so much, Fredrik. The reason I asked is because I found the
> specification completely opaque ...
>
> regards
> Steve
> --
> Steve Holden +1 571 484 6266 +1 800 494 3119
> Holden Web LLC http://www.holdenweb.com/
Here's the code to parse the spec.
#customize path
f= open( '\\windows\\fonts\\arial.ttf', 'rb' )
from struct import *
#header
shead= Struct( '>IHHHH' )
fhead= f.read( shead.size )
dhead= shead.unpack_from( fhead, 0 )
#font directory
stable= Struct( '>4sIII' )
ftable= f.read( stable.size* dhead[ 1 ] )
for i in range( dhead[1] ): #directory records
dtable= stable.unpack_from(
ftable, i* stable.size )
if dtable[0]== 'name': break
assert dtable[0]== 'name'
#name table
f.seek( dtable[2] ) #at offset
fnametable= f.read( dtable[3] ) #length
snamehead= Struct( '>HHH' ) #name table head
dnamehead= snamehead.unpack_from( fnametable, 0 )
sname= Struct( '>HHHHHH' )
for i in range( dnamehead[1] ): #name table records
dname= sname.unpack_from(
fnametable, snamehead.size+ i* sname.size )
if dname[3]== 4: #key == 4: "full name of font"
s= unpack_from(
'%is'% dname[4], fnametable,
dnamehead[2]+ dname[5] )[0]
print dname, s
This outputs:
(0, 3, 0, 4, 10, 318) A r i a l
(1, 0, 0, 4, 5, 4081) Arial
(3, 1, 1033, 4, 10, 318) A r i a l
First 3 fields:
0, 3, 0= Unicode, Unicode 2.0, English
1, 0, 0= Macintosh, Default, English
3, 1, 1033= Windows, Version 1.1, Language "1033"
More information about the Python-list
mailing list