Skip to content

ImageDraw.textsize() returns incorrect textsize for truetype fonts #644

@tk0miya

Description

@tk0miya

ImageDraw.textsize() does not return correct textsize for truetype fonts.
The return value does not include offset.

So I have to adjust offset using FreeTypeFont.getoffset() to get correct textsize.

from PIL import Image, ImageDraw, ImageFont

image = Image.new('RGB', (512, 256), (255, 255, 255))
drawer = ImageDraw.Draw(image)
font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeSerif.ttf', 32)

# drawing text
STRING = 'Hello, python language!'
drawer.text((10, 10), STRING, fill='black', font=font)

# drawing rectangle surrounding text
size = drawer.textsize(STRING, font=font)
offset = font.getoffset(STRING)
drawer.rectangle((10, 10, 10 + size[0] + offset[0], 10 + size[1] + offset[1]), outline='black')

image.save('example.png', 'PNG')

is this correct way?

And, I think ImageDraw.textsize() should return textsize including offset.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugAny unexpected behavior, until confirmed feature.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions