PIL ImageDraw.textsize returns the wrong height

I have a problem with the PIL ImageDraw module, in particular with the Draw.textsize method. It is assumed that this method accepts a string and a font and returns the width and height that the string will occupy when rendering in this font. It seems he has a lower bound on the height that he returns, though: I cannot convince him to return anything below 43 . Here is an example ( link ) to show what I'm looking at (bounding boxes drawn around text based on the returned width and height), and here is the code that created 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: %dx %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() 

As soon as the font size reaches size 38, the bounding rectangle is stretched to fit it correctly, but before that it set static 43 . The question is, does anyone know why ImageDraw behaves this way, and does anyone know how to fix it? I am currently working on a problem by setting:

 width = min(width, fontsize+1) 

... but this is obviously not the most reliable solution that has ever been developed.

+7
source share
1 answer

The main problem is that PIL is super buggy and is essentially no longer supported. The problem mentioned here is not the worst of them (for example, no one can replicate it because it is so difficult to even install it ...).

In light of all the problems that seem rampant in PIL 1.1.7, the best solution is to simply install Pillow and move forward. It does not require code changes for code that already runs PIL (this is the PIL fork, so it installs the PIL library), and it seems to be much friendlier (and still active). According to commentators on this issue, this is a simple, trouble-free installation, and it actually works as intended.

+2
source

All Articles