How I can load a font file with PIL.ImageFont.truetype without specifying the absolute path?

Posted on Mar 28, 2023

Question

When I write the code in Windows, this code can load the font file just fine:

ImageFont.truetype(filename='msyhbd.ttf', size=30);

I guess the font location is registered in Windows registry. But when I move the code to Ubuntu, and copy the font file over to /usr/share/fonts/, the code cannot locate the font:

 self.font = core.getfont(font, size, index, encoding)
 IOError: cannot open resource

How can I get PIL to find the ttf file without specifying the absolute path?

Answer

To me worked this on xubuntu:

from PIL import Image,ImageDraw,ImageFont

sample text and font

unicode_text = u"Hello World!" font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf", 28, encoding=“unic”)

get the line size

text_width, text_height = font.getsize(unicode_text)

create a blank canvas with extra space between lines

canvas = Image.new(‘RGB’, (text_width + 10, text_height + 10), “orange”)

draw the text onto the text canvas, and use blue as the text color

draw = ImageDraw.Draw(canvas) draw.text((5,5), u’Hello World!’, ‘blue’, font)

save the blank canvas to a file

canvas.save(“unicode-text.png”, “PNG”) canvas.show()

enter image description here

Windows version

from PIL import Image, ImageDraw, ImageFont

unicode_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:

enter image description here