Text Width Measurement (Python / PIL)

I use the following two methods to compute a string with a pattern width for a given font type and size:

font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 14)
sample = "Lorem ipsum dolor sit amet, partem periculis an duo, eum lorem paulo an, mazim feugiat lobortis sea ut. In est error eirmod vituperata, prima iudicabit rationibus mel et. Paulo accumsan ad sit, et modus assueverit eum. Quod homero adversarium vel ne, mel noster dolorum te, qui ea senserit argumentum complectitur. Duo at laudem explicari deterruisset, eu quo hinc mnesarchum. Vel autem insolens atomorum at, dolorum suavitate voluptatum duo ex."
#METHOD 1
draw_txt = ImageDraw.Draw(img)
width, height = draw_txt.textsize(sample, font=font)
print width
#METHOD 2
width = 0
for c in sample:
    width += font.getsize(c)[0]
print width

METHOD 1gives width 3236, while METHOD 2gives 3270. Why the discrepancy? Moreover, I also noticed that the smaller the example text, the less inconsistency between the two methods.

What happens under the hood? And what width can be considered as the true width of the sentence made? And finally, is there a way I can make both methods report approximately the same widths?

Note: Example text is 445 characters.

+4
1

:

  • .

, , - , .

Wikipedia :

- , . , ( ) . .

Kerning brings A and V closer together

DejaVuSans:

font kerning showing different char widths

. -.

, , , , , :

# METHOD 3
width = font.getsize(sample)[0]
print width

Pillow ImageDraw.textsize ( ):

def textsize(self, text, font=None, *args, **kwargs):
    """Get the size of a given string, in pixels."""
    if self._multiline_check(text):
        return self.multiline_textsize(text, font, *args, **kwargs)

    if font is None:
        font = self.getfont()
    return font.getsize(text)

font.getsize, . ( font.getsize.)

+5

Source: https://habr.com/ru/post/1676587/


All Articles