Cannot align text with line drawn on image

I am trying to manipulate images using the python Pillow library (fork of PIL) and am facing some strange problem. For some reason, when I try to draw a line and draw some text with the same y coordinate, they do not match. The text is slightly below the line, but for me both charts start from the same point. Has anyone had this problem before and / or knew how to solve it? Here is 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
+4
source share
2 answers

I get something like this (dimensions are 10 times smaller):

example test1.jpg output

, (x, y), ImageDraw.text(), top :

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

.

:

  • xy - .
  • - , .
  • font - ImageFont.
  • fill - , .

code: , xy.

+3

, , , , font.getsize(text)[1] . :

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
0

Source: https://habr.com/ru/post/1543926/


All Articles