ch1zra
ch1zra

Reputation: 183

python PIL chops top of my draw.text

I am using python and PIL to draw some text. I stumbled upon certain tutorial 'cause I needed some guides on how to center text within certain bounds:

the code works but it has some strange behavior. It eats the top of string. Here's how it should like http://img855.imageshack.us/img855/9292/qttempya4744.png

and here's how it looks http://img546.imageshack.us/img546/8541/outn.jpg

here's my code :

import os
from PIL import ImageDraw, ImageFont, Image
def draw_text(text, size, fill=None):
    font = ImageFont.truetype('C:\exl.ttf', 30)
    size = font.getsize(text)# Returns the width and height of the given text, as a 2-tuple.
    size = (size[0],size[1]+15)
    im = Image.new('RGBA', size, (0, 0, 0, 0)) # Create a blank image with the given size
    draw = ImageDraw.Draw(im)
    draw.text((0, 25), text, font=font, fill=fill) #Draw text
    return im

img = draw_text('zod', 30, (82, 124, 178))
img.save('C:\out.jpg',"JPEG")
print 'Complete!'
os.startfile('C:\out.jpg')

I have this bug with other fonts too (tried Arial and Verdana). help plz :)

Upvotes: 1

Views: 1761

Answers (1)

ch1zra
ch1zra

Reputation: 183

I have managed to fix this. It appears that drawtext has some issues with certain font sizes. I've done a bit of experimenting, and it can clearly be seen here that certain font sizes get their top chopped off http://img838.imageshack.us/img838/7677/pilfontsize.jpg

Code for testing above mentioned :

from PIL import ImageDraw, ImageFont, Image

im = Image.new('RGBA', (700, 1600), (0, 0, 0, 0)) 
fSize = 1
yVal = 1

while fSize <= 50:
    font = ImageFont.truetype('arial.ttf', fSize)
    fString = "This line is in Arial font size " + str(fSize)
    size = font.getsize(fString)
    draw = ImageDraw.Draw(im)
    draw.text((5, yVal), fString, font=font, fill=None)
    fSize += 1
    yVal += fSize + 5

Anyhow, I made it, and I'm proud :D This rendering issue should get worked into by developers of PIL.

Upvotes: 2

Related Questions