python-pillow / python-pillow/Pillow

Multiline text line height not being calculated correctly

Open
#1,646 35 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Conversion
Dominant language
Python
Stars
13.8k
Forks
2.5k
Avg merge
2d 8h
Merged PRs (30d)
89

Description

The line height isn't being calculated correctly for ImageDraw's multiline_text() function [1]. It's making an assumption that a capital "A" is as large as the font can be. However, if I use the word "Apple" you'll notice that the "p" in word creates a different text size.

The issue

Current code

line_spacing = self.textsize('A', font=font)[1] + spacing
>>> self.textsize('A', font=font)[1]
170
>>> self.textsize('APPLE', font=font)[1]
170
>>> self.textsize('Apple', font=font)[1]
244 // <-- problem

How the text correctly looks on the web

screen shot 2016-01-05 at 12 13 35 pm

How the image is rendered via pillow (incorrect line height)

screen shot 2016-01-05 at 12 13 49 pm

Proposed Change

import string
...
line_spacing = self.textsize(string.ascii_letters, font=font)[1] + spacing

Gets characters above and below the text baseline. Use every upper and lower letter in the alphabet since you'll notice in the font above, the lower case "l" is the character with the highest point.

When that change is made, you'll see the correct text height in the image:

screen shot 2016-01-05 at 12 50 51 pm

[1] https://github.com/python-pillow/Pillow/blob/master/PIL/ImageDraw.py#L269

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in PIL/ImageDraw.py at the multiline_text implementation and reproduce the reported textsize results with the example font and strings. Check how line_spacing is derived from glyph bounds, then verify that multiline rendering accounts for both ascenders and descenders without excessive spacing.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
computer-graphics
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.