Pillow: ImageFont.getsize() doesn't account for newlines

Created on 18 Jan 2018  路  4Comments  路  Source: python-pillow/Pillow

>>> import PIL.ImageFont
>>> font = PIL.ImageFont.truetype('/usr/share/fonts/TTF/LiberationSans-Regular.ttf', 14)
>>> font.getsize('foo')
(22, 13)
>>> font.getsize('foo\nbar')
(54, 13)

Pillow 4.3.0
Python 3.6.4

Most helpful comment

Can I interest you in ImageDraw.ImageDraw.textsize instead?

>>> from PIL import Image, ImageFont, ImageDraw
>>> font = ImageFont.truetype("/Library/Fonts/Arial.ttf", 14)
>>> im = Image.new('RGB', (100, 100))
>>> draw = ImageDraw.Draw(im)
>>> draw.textsize("foo", font)
(20, 13)
>>> draw.textsize("foo\nbar", font)
(21, 34)

All 4 comments

Could be a problem with that particular font. Arial works for me:

Python 3.6.4 (default, Dec 19 2017, 15:26:29)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import ImageFont
>>> font = ImageFont.truetype("/Library/Fonts/Arial.ttf", 14)
>>> font.getsize("foo")
(20, 13)
>>> font.getsize("foo\nbar")
(52, 13)
>>>

(Pillow 5.0.0)

No it obviously doesn't as the height doesn't increase.

Oops, I just looked at the X change!

Can I interest you in ImageDraw.ImageDraw.textsize instead?

>>> from PIL import Image, ImageFont, ImageDraw
>>> font = ImageFont.truetype("/Library/Fonts/Arial.ttf", 14)
>>> im = Image.new('RGB', (100, 100))
>>> draw = ImageDraw.Draw(im)
>>> draw.textsize("foo", font)
(20, 13)
>>> draw.textsize("foo\nbar", font)
(21, 34)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

naaaargle picture naaaargle  路  3Comments

nomarek picture nomarek  路  3Comments

boskicthebrain picture boskicthebrain  路  4Comments

HansHirse picture HansHirse  路  3Comments

readyready15728 picture readyready15728  路  4Comments