PIL font size not changing

Viewed 1522

I am setting up a program to write some numbers on an image. The font size will change based on where it's writing (this size will be hardcoded).

After reading the docs, i am using ImageFont.truetype('font.ttf', fontSize) to load my font, with fontSize = 400.

from PIL import Image, ImageDraw, ImageFont

image = Image.open('base.jpg')
draw = ImageDraw.Draw(image);
fontSize = 400
font = ImageFont.truetype('font.ttf', fontSize)

color = 'rgb(0, 0, 0)'

def drawInfo():
    draw.text((50, 200), '20', fill=color, font=font)
    image.save('newVersion.jpg')

drawInfo()

Font: https://fonts.google.com/specimen/Kalam?selection.family=Kalam

base.jpg : https://ibb.co/6XQbxHv

newVersion.jpg : https://ibb.co/7XFRTyg

The expected result would be that the little 20 in the top left corner under strength will be huge (with the font size being 400). Unfortunately, it seems to just be the default size. What am I doing wrong?

2 Answers

The short answer is that 400 was too big a number, but if you are wondering why it then caused your font to become the default size, I will take you through a short journey.

Firstly, in your code, you use font = ImageFont.truetype('font.ttf', 400). This deploys the truetype function in the ImageFont library, which calls FreeTypeFont:

    def freetype(font):
        return FreeTypeFont(font, size, index, encoding, layout_engine)

    try:
        return freetype(font)
    except IOError:

The interesting part is what happens in FreeTypeFont, as below:

enter image description here

The FreeTypeFont calls core.getfont, which actually uses the _imagingft.c library, and this is where the font size of 400 killed the _imagingft getfont function, which gave up loading the text and threw an error:

enter image description here

Finally, if you remember the first function, truetype, it actually has a try: except IOError:, which causes it to call the FreeTypeFont function with no font size, making it default to 10, and causing your current issue:

enter image description here

Essentially, the solution is to try the maximum font size that will not break the _imagingft library, or to make use of a different library to load the fonts.

400 was most likely too big a number, after reducing it to 75 it worked fine.

Related