Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python image library - font positioning

EDIT: added complete 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 generates the following image:

enter image description here

It seems that when writing the text PIL library adds some margin at the top. This margin depends on the font I use.

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

(Using Python 2.7.6 with Pillow 2.3.0 on Ubuntu 14.04)

like image 625
Filip Avatar asked Jan 04 '16 18:01

Filip


1 Answers

I don't understand why, but subtracting font.getoffset(text)[1] from the y co-ordinate 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")
like image 145
Robᵩ Avatar answered Sep 18 '22 10:09

Robᵩ