Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL ImageDraw.textsize returns incorrect height

I'm having an issue with PIL's ImageDraw module, specifically the Draw.textsize method. This method is supposed to take a string and a font, and return the width and height that the string would occupy when rendered in that font. It seems to have a lower bound on the height that it returns, though: I can't convince it to return anything lower than 43. Here's an example (link) to show what I'm looking at (bounding boxes drawn around the text based on the returned width & height), and here's the code that produced it:

from PIL import Image, ImageDraw, ImageFont # PIL 1.1.7; Python 2.6.6

im = Image.open(r'C:\test\blank.png').convert('RGB')
draw = ImageDraw.Draw(im)

TEXTCOLOR = (0, 0, 0)
X = 10
Y = 3

for fontsize in xrange(8, 51):
    # Other fonts behave the same way
    font = ImageFont.truetype('Arial.ttf', fontsize)

    text = 'Hello, World! Size %d' % fontsize

    width, height = draw.textsize(text, font=font)
    print 'Font size %d: %d x %d' % (fontsize, width, height)

    bbox = [(X, Y), (X+width, Y+height)]
    draw.rectangle(bbox, outline=TEXTCOLOR)
    draw.text((X, Y), text, font=font, fill=TEXTCOLOR)
    Y += height + 3

im.show()

Once the font gets up to about size 38, the bounding box stretches to match it correctly, but before that, it's set to a static 43. The question is, does anyone know why ImageDraw is behaving this way, and does anyone know of a way to fix it? I'm currently working around the issue by setting:

width = min(width, fontsize+1)

...but that's obviously not the most robust solution ever devised.

like image 907
Henry Keiter Avatar asked Apr 18 '13 16:04

Henry Keiter


1 Answers

The basic issue seems to be that PIL is super buggy and essentially no longer supported. The problem mentioned here isn't the worst of it (e.g. no one is able to replicate it because it's so hard to even install...).

In light of all the troubles that seem to be rampant in PIL 1.1.7, the best solution seems to be to simply install Pillow and move along. It doesn't require code changes for code that already runs PIL (it's a PIL fork so it installs the "PIL" library), and it seems to be vastly friendlier (and still active). As the commenters on the question have confirmed, it's a simple, trouble-free install and it actually works like it's supposed to.

like image 158
Henry Keiter Avatar answered Oct 20 '22 12:10

Henry Keiter