ImageFont getsize () not getting the correct text size?

I use the following two methods to create a text preview image for a .ttf font file.

PIL Method:

def make_preview(text, fontfile, imagefile, fontsize=30):
    try:
        font = ImageFont.truetype(fontfile, fontsize)
        text_width, text_height = font.getsize(text)
        img = Image.new('RGBA', (text_width, text_height))
        draw = ImageDraw.Draw(img)
        draw.text((0, 0), text, font=font, fill=(0, 0, 0))
        return True
    except:
        return False

ImageMagick Method:

def make_preview(text, fontfile, imagefile, fontsize=30):
    p = subprocess.Popen(['convert', '-font', fontfile, '-background',
            'transparent', '-gravity', 'center', '-pointsize', str(fontsize),
            '-trim', '+repage', 'label:%s' % text, image_file])
    return p==0

Both methods create the correct preview images most of the time, but in some rare cases (<2%) the .getsize font (text) simply cannot get the correct text size, which causes the text to overflow, provided that it is canvas. ImageMagick has the same problem.

Example fonts and previews:

HANFORD.TTF http://download.appfile.com/HANFORD.png

NEWTOW.TTF http://download.appfile.com/NEWTOW.png

MILF.TTF http://download.appfile.com/MILF.png

SWANSE.TTF http://download.appfile.com/SWANSE.png

ImageMagick http://www.imagemagick.org/Usage/text/#overflow.

, , ?

+5
3

ImageMagick , , .

def make_preview(text, fontfile, imagefile, fontsize=30):
    p = subprocess.call(['convert', '-font', fontfile, '-background', 
        'transparent', '-gravity', 'center', '-size', '1500x300',
        '-pointsize', str(fontsize),  '-trim', '+repage', 'label:%s' % text, image_file]) 
    return p==0 

, , .

PIL , , , .

+1

alt text http://img9.imageshack.us/img9/2419/fontfix.jpg

, , ( , Arial, ), ( / ). ,

Hanford Script , , , , , .

. , : , "Handford Script" , img=img.crop(img.getbbox())

alt text http://img64.imageshack.us/img64/1903/hanfordfontworkaround.jpg

UPDATE2: = (255,255,255) Image.New,

img = Image.new('RGBA', (text_width, text_height),color=(255,255,255))

alt text http://img245.imageshack.us/img245/3462/colorblackh.jpg

+5

PHP ImageMagick.

In the end, I solved this by drawing the text on a very large canvas, and then cropping it using trim / auto-crop functions that shave the extra space from the image.

If I understand your preview function correctly, it actually does just that: this is enough to simply remove the width and height settings.

+2
source