-
Hello, I have a question about calculating text bounding boxes. Is there a method that can calculate a bounding box of a given text without an actual image object? The problem I having is that I need to have image size calculated beforehand. And to do this I need to get size of multiline text. So to create an image I need its size and to calculate the size I need to use Solutions I've already tried:
import os
from PIL import ImageFont
font = ImageFont.truetype(os.path.join('fonts', 'OpenSans-Regular.ttf'), 14)
print(font.getbbox('line 1')) # (0, 4, 37, 15)
print(font.getbbox('line 1\nline 2\nline 3')) # (0, 4, 127, 15)
import os
from PIL import ImageFont
font = ImageFont.truetype(os.path.join('fonts', 'OpenSans-Regular.ttf'), 14)
print(font.getsize_multiline('line 1\nline 2\nline 3')) # (37, 53)
# DeprecationWarning: getsize_multiline is deprecated and will be removed in Pillow 10 (2023-07-01). Use ImageDraw.multiline_textbbox instead.
import os
from PIL import Image
from PIL import ImageFont
from PIL.ImageDraw import ImageDraw
font = ImageFont.truetype(os.path.join('fonts', 'OpenSans-Regular.ttf'), 14)
draw = ImageDraw(Image.new('RGB', (0, 0)))
print(draw.multiline_textbbox((0, 0), 'line 1', font)) # (0, 4, 37, 15)
print(draw.multiline_textbbox((0, 0), 'line 1\nline 2\nline 3', font)) # (0, 4, 37, 53) Am I missing something or is there really no way to achieve this? And if there isn't why an image is required to calculate a size of text? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is currently the best option. All multiline text operations, except for |
Beta Was this translation helpful? Give feedback.
This is currently the best option.
All multiline text operations, except for
font.getsize_multiline
(IIRC an exact duplicate ofdraw.multiline_textsize
), are handled inImageDraw
which requires an Image. Moving thedraw.multiline_text
operation toImageFont
would require significant changes (either rewriting the function in C or taking a significant performance penalty), anddraw.multiline_textbbox
is quite long (~100 lines), too long to feel good about duplicating the code inImageFont
.