Python Image Library - Font Placement

EDIT : added full working example

I have the following program:

from PIL import Image, ImageDraw, ImageFont FULL_SIZE = 50 filename = 'font_test.png' font="/usr/share/fonts/truetype/msttcorefonts/arial.ttf" text="5" image = Image.new("RGBA", (FULL_SIZE, FULL_SIZE), color="grey") draw = ImageDraw.Draw(image) font = ImageFont.truetype(font, 40) font_width, font_height = font.getsize(text) draw.rectangle(((0, 0), (font_width, font_height)), fill="black") draw.text((0, 0), text, font=font, fill="red") image.save(filename, "PNG") 

This creates the following image:

enter image description here

It seems that when writing text, the PIL library adds some margin at the top. This stock depends on the font used.

How can I take this into account when trying to place text (I want it to be in the middle of the rectangle)?

(Using Python 2.7.6 with Pillow 2.3.0 on Ubuntu 14.04)

+6
source share
1 answer

I don’t understand why, but subtracting font.getoffset(text)[1] from the y coordinate fixes it on my computer.

 from PIL import Image, ImageDraw, ImageFont FULL_SIZE = 100 filename = 'font_posn_test.png' fontname = '/usr/share/fonts/truetype/msttcorefonts/arial.ttf' textsize = 40 text = "5" image = Image.new("RGBA", (FULL_SIZE, FULL_SIZE)) draw = ImageDraw.Draw(image) font = ImageFont.truetype(fontname, textsize) print font.getoffset(text) print font.font.getsize(text) font_width, font_height = font.getsize(text) font_y_offset = font.getoffset(text)[1] # <<<< MAGIC! draw.rectangle(((0, 0), (font_width, font_height)), fill="black") draw.text((0, 0 - font_y_offset), text, font=font, fill="red") image.save(filename, "PNG") 
+5
source

All Articles