How I can load a font file with PIL.ImageFont.truetype without specifying the absolute path?
To me worked this on xubuntu:
from PIL import Image,ImageDraw,ImageFont# sample text and fontunicode_text = u"Hello World!"font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf", 28, encoding="unic")# get the line sizetext_width, text_height = font.getsize(unicode_text)# create a blank canvas with extra space between linescanvas = Image.new('RGB', (text_width + 10, text_height + 10), "orange")# draw the text onto the text canvas, and use black as the text colordraw = ImageDraw.Draw(canvas)draw.text((5,5), u'Hello World!', 'blue', font)# save the blank canvas to a filecanvas.save("unicode-text.png", "PNG")canvas.show()
Windows version
from PIL import Image, ImageDraw, ImageFontunicode_text = u"Hello World!"font = ImageFont.truetype("arial.ttf", 28, encoding="unic")text_width, text_height = font.getsize(unicode_text)canvas = Image.new('RGB', (text_width + 10, text_height + 10), "orange")draw = ImageDraw.Draw(canvas)draw.text((5, 5), u'Hello World!', 'blue', font)canvas.save("unicode-text.png", "PNG")canvas.show()
The output is the same as above:
According to the PIL documentation, only Windows font directory is searched:
On Windows, if the given file name does not exist, the loader also looks in Windows fonts directory.
http://effbot.org/imagingbook/imagefont.htm
So you need to write your own code to search for the full path on Linux.
However, Pillow, the PIL fork, currently has a PR to search a Linux directory. It's not exactly clear yet which directories to search for all Linux variants, but you can see the code here and perhaps contribute to the PR:
There is a Python fontconfig package, whereby one can access system font configuration, The code posted by Jeeg_robot can be changed like so:
from PIL import Image,ImageDraw,ImageFontimport fontconfig# find a font filefonts = fontconfig.query(lang='en')for i in range(1, len(fonts)): if fonts[i].fontformat == 'TrueType': absolute_path = fonts[i].file break# the rest is like the original code:# sample text and fontunicode_text = u"Hello World!"font = ImageFont.truetype(absolute_path, 28, encoding="unic")# get the line sizetext_width, text_height = font.getsize(unicode_text)# create a blank canvas with extra space between linescanvas = Image.new('RGB', (text_width + 10, text_height + 10), "orange")# draw the text onto the text canvas, and use black as the text colordraw = ImageDraw.Draw(canvas)draw.text((5,5), u'Hello World!', 'blue', font)# save the blank canvas to a filecanvas.save("unicode-text.png", "PNG")canvas.show()