Tim S
Tim S

Reputation: 5101

Cannot align text with a line drawn on an image

I'm trying to do some image manipulation with the python library Pillow (fork of PIL) and am coming across a weird problem. For some reason, when I try to draw a line and draw some text at the same y coordinate, they're not matching up. The text is a bit below the line, yet I have both graphics starting at the same point. Has anyone had this problem before and/or know how to solve it? Here's the code I'm using:

image = Image.open("../path_to_image/image.jpg")

draw = ImageDraw.Draw(image)

font = ImageFont.truetype("../fonts/Arial Bold.ttf", 180)

draw.line((0,2400, 500,2400), fill="#FFF", width=1)
draw.text((0, 2400), "Test Text", font=font) 

image.save(os.path.join(root, "test1.jpg"), "JPEG", quality=100)

return

Upvotes: 4

Views: 1049

Answers (2)

Tim S
Tim S

Reputation: 5101

For those with a similar problem, I ended up creating a helper function that manually adjusts the font size until font.getsize(text)[1] returns the correctly sized text. Here's a snippet:

def adjust_font_size_to_line_height(font_location, desired_point_size, text):
    adjusted_points = 1

    while True:
        font = ImageFont.truetype(font_location, adjusted_points)
        height = font.getsize(text)[1]

        if height != desired_point_size:
            adjusted_points += 1
        else:
            break

    return adjusted_points

Upvotes: 0

Hugo
Hugo

Reputation: 29344

I get something similar (with sizes 10 times smaller):

example test1.jpg output

This is happening because the (x,y) coordinates given to ImageDraw.text() are the top left corner of the text:

PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None)

Draws the string at the given position.

Parameters:

  • xy – Top left corner of the text.
  • text – Text to be drawn.
  • font – An ImageFont instance.
  • fill – Color to use for the text.

This is confirmed in the code: the text is turned into a bitmap and then drawn at xy.

Upvotes: 3

Related Questions