Short answer

Load a font with ImageFont.truetype("DejaVuSans.ttf", 32); the size is in pixels. Measure with font.getbbox(text) (the ink box) or font.getlength(text) (the advance width). To fit text into a box on Pillow 12.2 or newer, use ImageText.Text(text, font).wrap(width, height, "shrink") and draw the result with ImageDraw.text().

What getbbox, getlength and getmetrics measure

The text Hxgé with coloured lines for ascent, baseline and descent, a red box around the ink and a purple line at the advance width
Real output. Red: getbbox(). Blue, green, orange: ascent, baseline, descent from getmetrics(). Purple: getlength().
font_metrics.py
from PIL import Image, ImageDraw, ImageFont

font = ImageFont.truetype("DejaVuSans.ttf", 120)
text = "Hxgé"
ascent, descent = font.getmetrics()
print("size:", font.size, "| getmetrics() ascent, descent:", (ascent, descent))
print("getbbox(text):", font.getbbox(text), "| getlength(text):", font.getlength(text))
print("getbbox with anchor='ls':", font.getbbox(text, anchor="ls"))

img = Image.new("RGB", (560, 250), "white")
d = ImageDraw.Draw(img)
x, base = 40, 180                                        # draw with the baseline at y = 180
d.text((x, base), text, font=font, fill=(40, 40, 40), anchor="ls")
l, t, r, b = font.getbbox(text, anchor="ls")
d.rectangle((x + l, base + t, x + r, base + b), outline=(230, 60, 60), width=2)          # ink box: getbbox
for y, colour, label in [(base - ascent, (40, 120, 230), "ascent"), (base, (20, 160, 90), "baseline"),
                         (base + descent, (200, 120, 20), "descent")]:
    d.line((10, y, 550, y), fill=colour, width=2)
    d.text((548, y - 2), label, font=ImageFont.truetype("DejaVuSans.ttf", 16), fill=colour, anchor="rb")
adv = x + font.getlength(text)
d.line((adv, 30, adv, 235), fill=(150, 60, 200), width=2)                                 # advance: getlength
d.text((adv + 4, 235), "getlength", font=ImageFont.truetype("DejaVuSans.ttf", 16), fill=(150, 60, 200), anchor="lb")
img.save("metrics.png")
Output
size: 120 | getmetrics() ascent, descent: (112, 29)
getbbox(text): (0, 16, 311, 137) | getlength(text): 311.25
getbbox with anchor='ls': (0, -96, 311, 25)
  • getbbox(text) is the box around the ink, relative to the anchor. With the default anchor "la" (left, ascender) its top is not 0: it is the gap between the font's ascender line and the top of the tallest glyph in this text. That gap is why text drawn at (x, y) does not start exactly at y.
  • getlength(text) is the advance: where the next character would go. It can be smaller or larger than the ink width (italic overhangs, trailing spaces count).
  • getmetrics() is the same for any text: use ascent + descent as a stable line height, so lines with and without descenders line up.

The textsize() method these replace was removed in Pillow 10; see 'ImageDraw' object has no attribute 'textsize' for a drop-in replacement, and anchors for placing text by its centre or baseline.

Font size: pixels, not points

font_size.py
from PIL import ImageFont

for size in [12, 24, 48, 96]:
    f = ImageFont.truetype("DejaVuSans.ttf", size)
    ascent, descent = f.getmetrics()
    cap = f.getbbox("H")
    print(f"size={size:<3} line height {ascent + descent:>3} px   capital H {cap[3] - cap[1]:>3} px tall")

print("float sizes work:", ImageFont.truetype("DejaVuSans.ttf", 10.5).size)


def points_to_pixels(points, dpi):
    return round(points * dpi / 72)                      # 1 point = 1/72 inch


for pt, dpi in [(12, 72), (12, 96), (12, 300)]:
    print(f"{pt} pt at {dpi} dpi = size={points_to_pixels(pt, dpi)}")
Output
size=12  line height  15 px   capital H   9 px tall
size=24  line height  29 px   capital H  18 px tall
size=48  line height  57 px   capital H  35 px tall
size=96  line height 113 px   capital H  70 px tall
float sizes work: 10.5
12 pt at 72 dpi = size=12
12 pt at 96 dpi = size=16
12 pt at 300 dpi = size=50

The size argument is the em size in pixels. A line of DejaVu Sans is about 1.18× that tall and a capital letter about 0.73×; other fonts differ, so measure rather than assume. Coming from a word processor, convert points with pixels = points × dpi / 72: 12 pt text for a 300 dpi print needs size=50.

Loading fonts: files, bytes, variants and .ttc collections

load_fonts.py
import io
from PIL import ImageFont

with open("DejaVuSans.ttf", "rb") as fh:
    data = fh.read()
from_bytes = ImageFont.truetype(io.BytesIO(data), 32)    # from memory: a download, a database, a zip
print("from bytes:", from_bytes.getname())

bigger = from_bytes.font_variant(size=64)                 # same font, another size, without reloading the file by hand
print("font_variant:", bigger.size, bigger.getname())

try:
    ImageFont.truetype("arial.ttf", 32)
except OSError as e:
    print("missing font:", e)

# A .ttc collection holds several fonts; index= picks one. Built here from the two DejaVu files with fontTools,
# so the example runs anywhere (real ones: Helvetica.ttc, msgothic.ttc, NotoSansCJK.ttc).
from fontTools.ttLib import TTCollection, TTFont
collection = TTCollection()
collection.fonts = [TTFont("DejaVuSans.ttf"), TTFont("DejaVuSans-Bold.ttf")]
collection.save("DejaVu.ttc")
for i in range(2):
    print(f"index={i}:", ImageFont.truetype("DejaVu.ttc", 32, index=i).getname())
Output
from bytes: ('DejaVu Sans', 'Book')
font_variant: 64 ('DejaVu Sans', 'Book')
missing font: cannot open resource
index=0: ('DejaVu Sans', 'Book')
index=1: ('DejaVu Sans', 'Bold')

A bare file name is looked up in the system font folders (Windows' Fonts folder, the macOS font libraries, ~/.fonts and /usr/share/fonts on Linux), so "arial.ttf" works on Windows and fails elsewhere with cannot open resource. Shipping the font file next to your code is the portable fix; the cannot open resource page covers every case. font_variant() is the way to get the same font at several sizes, for example in a shrink-to-fit loop.

load_default(): the font that always works

default_font.py
from PIL import ImageFont, features

print("FreeType available:", features.check("freetype2"))
f = ImageFont.load_default()
print("load_default():", type(f).__name__, f.size, f.getname())
big = ImageFont.load_default(size=48)
print("load_default(size=48):", type(big).__name__, big.size, "| bbox of 'Hello':", big.getbbox("Hello"))
old = ImageFont.load_default_imagefont()                 # the tiny bitmap font, what you get without FreeType
print("load_default_imagefont():", type(old).__name__, "| bbox of 'Hello':", old.getbbox("Hello"))
Output
FreeType available: True
load_default(): FreeTypeFont 10 ('Aileron', 'Regular')
load_default(size=48): FreeTypeFont 48 | bbox of 'Hello': (0, 11, 112, 48)
load_default_imagefont(): ImageFont | bbox of 'Hello': (0, 0, 30, 11)

Since Pillow 10.1, load_default() returns a real scalable font (Aileron Regular, bundled with Pillow) whenever FreeType is available, which is true for every wheel on PyPI. Pass size= to make it readable; the old 11-pixel bitmap font is still there as load_default_imagefont().

Kerning, ligatures and the two layout engines

layout_engines.py
import time
from PIL import Image, ImageDraw, ImageFont, features

print("raqm (complex text layout) available:", features.check("raqm"))
raqm = ImageFont.truetype("DejaVuSans.ttf", 48)          # RAQM is the default when available
basic = ImageFont.truetype("DejaVuSans.ttf", 48, layout_engine=ImageFont.Layout.BASIC)
print(f"{'text':<8}{'RAQM':>8}{'BASIC':>8}{'no kern':>9}{'no liga':>9}")
for t in ["AV", "To", "ffi", "office"]:
    print(f"{t:<8}{raqm.getlength(t):8.1f}{basic.getlength(t):8.1f}"
          f"{raqm.getlength(t, features=['-kern']):9.1f}{raqm.getlength(t, features=['-liga']):9.1f}")

img = Image.new("L", (1200, 80), 255)
d = ImageDraw.Draw(img)
line = "The quick brown fox jumps over the lazy dog. 0123456789"
for name, font in [("RAQM", raqm), ("BASIC", basic)]:
    runs = []
    for _ in range(5):
        t0 = time.perf_counter()
        for _ in range(50):
            d.text((0, 0), line, font=font, fill=0)
        runs.append((time.perf_counter() - t0) * 1000 / 50)
    print(f"{name:<6} draw one line: {min(runs):.2f} ms")
Output
raqm (complex text layout) available: True
text        RAQM   BASIC  no kern  no liga
AV          62.6    66.0     65.7     62.6
To          50.5    57.9     58.7     50.5
ffi         46.4    47.0     46.4     47.2
office     131.7   132.0    131.7    132.5
RAQM   draw one line: 0.50 ms
BASIC  draw one line: 0.48 ms

RAQM (the default whenever libraqm is found, which the PyPI wheels bundle) shapes text with HarfBuzz: it applies kerning (“AV” and “To” move closer), ligatures (“ffi” becomes one glyph) and the joining and reordering that Arabic, Hebrew and Indic scripts need. BASIC uses FreeType alone: here it applied neither kerning nor ligatures, and it cannot shape complex scripts. For this Latin line both engines took the same time (0.50 ms and 0.48 ms), so there is no speed reason to switch to BASIC. Turn OpenType features on or off per call with features=["-kern", "-liga"], and set direction="rtl" and language= for right-to-left text. Pillow 13 wheels link FreeType against the HarfBuzz that Pillow ships, which the release notes say may slightly change rendering for fonts that rely on FreeType's auto-hinter.

Variable fonts

The words Pillow 13 drawn six times in Oswald, from weight 200 (thin) to 700 (bold), with each width in pixels
Real output: one font file, six weights.
variable_font.py
from PIL import Image, ImageDraw, ImageFont

font = ImageFont.truetype("Oswald-Variable.ttf", 54)    # a variable font with a weight axis
print("named styles:", [n.decode() for n in font.get_variation_names()])
print("axes:", font.get_variation_axes())

img = Image.new("RGB", (1000, 300), "white")
d = ImageDraw.Draw(img)
label = ImageFont.truetype("DejaVuSans.ttf", 16)
for i, weight in enumerate([200, 300, 400, 500, 600, 700]):
    font.set_variation_by_axes([weight])                 # one value per axis, in the order of get_variation_axes()
    x, y = (i % 3) * 330 + 20, (i // 3) * 150 + 20
    d.text((x, y), "Pillow 13", font=font, fill=(30, 30, 30))
    d.text((x, y + 92), f"wght {weight}  |  {font.getlength('Pillow 13'):.0f} px wide", font=label, fill=(120, 120, 120))
img.save("variable.png")
font.set_variation_by_name("Bold")                       # a named style, after axes were set on this object...
print("set_variation_by_name('Bold') now:", font.getlength("Pillow 13"), "px wide (the default weight, not bold)")
bold = ImageFont.truetype("Oswald-Variable.ttf", 54)     # ...works on a font object whose axes were never set
bold.set_variation_by_name("Bold")
print("on a freshly loaded font:", bold.getlength("Pillow 13"), "px wide")
Output
named styles: ['ExtraLight', 'Light', 'Regular', 'Medium', 'SemiBold', 'Bold']
axes: [{'minimum': 200, 'default': 400, 'maximum': 700, 'name': b'Weight'}]
set_variation_by_name('Bold') now: 176.234375 px wide (the default weight, not bold)
on a freshly loaded font: 195.421875 px wide

A variable font holds a whole family in one file. Set a named style with set_variation_by_name() or any value on its axes with set_variation_by_axes(). Both change the font object in place, so load one object per weight you need at the same time. The last two lines show a trap measured on Pillow 13.0.0: once axes have been set on an object, set_variation_by_name() falls back to the default weight instead of the named style. Either keep using axis values (Bold is [700] here) or load the font again for named styles; font_variant() also gives a fresh object, at the default weight. A font without variations raises OSError from these methods.

Glyph masks and rotated text

masks_and_rotation.py
from PIL import Image, ImageDraw, ImageFont

font = ImageFont.truetype("DejaVuSans-Bold.ttf", 40)
mask, offset = font.getmask2("Pillow", mode="L")        # the rendered glyphs as a greyscale coverage mask
print("getmask2:", mask.size, "offset", offset, "| values", Image.frombytes("L", mask.size, bytes(mask)).getextrema())

vertical = ImageFont.TransposedFont(font, Image.Transpose.ROTATE_90)
img = Image.new("RGB", (120, 260), "white")
ImageDraw.Draw(img).text((40, 10), "Pillow", font=vertical, fill="black")
print("TransposedFont bbox:", vertical.getbbox("Pillow"), "(width and height swapped)")
img.save("vertical.png")
Output
getmask2: (135, 30) offset (0, 8) | values (0, 255)
TransposedFont bbox: (0, 0, 30, 135) (width and height swapped)

getmask2() gives the rendered coverage of the text as a greyscale mask, which is what ImageDraw pastes through. Use it to cut text out of an image or to build effects from the shape of the letters. TransposedFont turns text by 90° steps without rotating a whole image afterwards; for any other angle, draw on a transparent image and rotate(expand=True) it (see rotated text).

ImageText.Text: text as an object

imagetext_basics.py
from PIL import Image, ImageDraw, ImageFont, ImageText

font = ImageFont.truetype("DejaVuSans-Bold.ttf", 48)
title = ImageText.Text("Launch day", font)
print("get_length():", title.get_length(), "| get_bbox():", title.get_bbox())
title.stroke(3, (20, 20, 20))                            # outline is part of the text object now
print("with stroke:", title.get_bbox(), "(3 px larger on every side)")

img = Image.new("RGB", (420, 110), (90, 160, 230))
ImageDraw.Draw(img).text((20, 20), title, fill="white")  # draw() accepts a Text instead of a string
img.save("title.png")
Output
get_length(): 307.25 | get_bbox(): (0, 9, 307, 55)
with stroke: (-3, 6, 310, 58) (3 px larger on every side)

ImageText.Text (new in Pillow 12.0) keeps the string, font, spacing, direction, features, outline and colour-emoji setting together. You measure and draw the same object, so measurements cannot drift from what is drawn because one call forgot a stroke_width argument.

Wrap, shrink and grow text to fit a box

Four panels with a red box: text wrapped to the width but overflowing the height, wrapped and cut at the box, shrunk to fit and a short word grown to fill the box
Real output of the script below.
wrap_to_box.py
from PIL import Image, ImageDraw, ImageFont, ImageText

story = ("Pillow 12.2 added ImageText.Text.wrap(), which breaks text into lines that fit a width "
         "and can also shrink or grow the font until the text fills a box.")
box_w, box_h = 360, 200


def panel(text, label):
    img = Image.new("RGB", (box_w + 40, box_h + 70), "white")
    d = ImageDraw.Draw(img)
    d.rectangle((19, 19, 20 + box_w, 20 + box_h), outline=(220, 60, 60))
    d.text((20, 20), text, fill=(30, 30, 30))
    d.text((20, box_h + 34), label, font=ImageFont.truetype("DejaVuSans.ttf", 15), fill=(110, 110, 110))
    return img


a = ImageText.Text(story, ImageFont.truetype("DejaVuSans.ttf", 30))
a.wrap(box_w)                                            # width only: changes a.text in place
print("wrap(width):", a.text.count("\n") + 1, "lines, height", a.get_bbox()[3])

b = ImageText.Text(story, ImageFont.truetype("DejaVuSans.ttf", 30))
rest = b.wrap(box_w, box_h)                              # with a height: what does not fit comes back
print("wrap(width, height): left over ->", repr(rest.text if rest else None))

c = ImageText.Text(story, ImageFont.truetype("DejaVuSans.ttf", 40))
c.wrap(box_w, box_h, "shrink")                           # smaller font until everything fits
print("shrink: font size 40 ->", c.font.size)

g = ImageText.Text("Lift-off", ImageFont.truetype("DejaVuSans-Bold.ttf", 10))
g.wrap(box_w, box_h, "grow")                             # larger font while it still fits
print("grow: font size 10 ->", g.font.size)

panels = [panel(a, "wrap(width): overflows the box"), panel(b, "wrap(width, height): stops at the box"),
          panel(c, f"wrap(w, h, 'shrink'): size {c.font.size}"), panel(g, f"wrap(w, h, 'grow'): size {g.font.size}")]
sheet = Image.new("RGB", (2 * (box_w + 40), 2 * (box_h + 70)), "white")
for i, p in enumerate(panels):
    sheet.paste(p, ((i % 2) * (box_w + 40), (i // 2) * (box_h + 70)))
sheet.save("wrap.png")
Output
wrap(width): 7 lines, height 220
wrap(width, height): left over -> ' text fills a box.'
shrink: font size 40 -> 21
grow: font size 10 -> 94

wrap(width) breaks lines at spaces and changes the text in place. Add height and the lines that do not fit come back as a new Text (handy for paginating), or pass "shrink" or "grow" to have Pillow search for the font size. A tuple such as ("shrink", 12) sets the limit at which it gives up. On Pillow older than 12.2, the add-text guide has a tested hand-written wrapper.

What wrap() cannot do

wrap_limits.py
from PIL import ImageFont, ImageText

font = ImageFont.truetype("DejaVuSans.ttf", 30)
try:
    ImageText.Text("Supercalifragilisticexpialidocious", font).wrap(150)
except ValueError as e:
    print("one long word in 150 px: ValueError:", e)

for scaling in [("shrink", 20), "grow"]:
    try:
        ImageText.Text("A long sentence that will not fit", ImageFont.truetype("DejaVuSans.ttf", 30)).wrap(100, 30, scaling)
    except ValueError as e:
        print(f"wrap(100, 30, {scaling!r}): ValueError: {e}")
try:
    ImageText.Text("rtl text", font, direction="rtl").wrap(100)
except ValueError as e:
    print("direction='rtl': ValueError:", e)
Output
one long word in 150 px: ValueError: Word does not fit within line
wrap(100, 30, ('shrink', 20)): ValueError: Text could not be scaled
wrap(100, 30, 'grow'): ValueError: Text could not be scaled
direction='rtl': ValueError: Only ltr direction supported

wrap() never breaks inside a word: a single word wider than the box raises ValueError, so catch it for user-supplied text (long URLs are the usual culprit) and fall back to a smaller font or a character-level split. Scaling raises ValueError when no size within the limit fits (shrink) or when even the starting size does not fit (grow), and wrapping is only implemented for left-to-right text.

The complete API

Generated from Pillow 13.0.0, so the lists and signatures are complete for that version.

ImageFont functions 5

Name and signatureWhat it does
load(filename)Loads a bitmap font in Pillow's own .pil format (with its .pbm/.png glyph file). Accepts pathlib.Path since Pillow 13.
load_default(size=None)The built-in font. With FreeType (every wheel) it is Aileron Regular as a FreeTypeFont at size (default 10); without FreeType, the tiny bitmap font.
load_default_imagefont()Always the tiny built-in bitmap font (an ImageFont.ImageFont, fixed size).
load_path(filename)Like load(), but searches sys.path for the file.
truetype(font, size=10, index=0, encoding='', layout_engine=None)Loads a TrueType/OpenType font (.ttf, .otf, .ttc) from a path, a file name in the system font folders, or a binary file object. size is in pixels and may be a float; index picks a font in a collection.

ImageFont classes 6

Name and signatureWhat it does
Axis(...)A TypedDict describing one variation axis: minimum, default, maximum, name.
BaseImageFont()The common base class of ImageFont and FreeTypeFont; useful for type hints.
FreeTypeFont(font, size=10, index=0, encoding='', layout_engine=None)A loaded TrueType/OpenType font at one size. Returned by truetype() and load_default(size=).
ImageFont()A bitmap font from load() or load_default_imagefont(): fixed size, no anchors other than the default.
Layout(*values)Text layout engines: BASIC (FreeType only) and RAQM (HarfBuzz shaping, bidirectional text).
TransposedFont(font, orientation=None)Wraps a font so that text is drawn rotated or flipped by a Transpose operation.

FreeTypeFont methods 11

Name and signatureWhat it does
font_variant(font=None, size=None, index=None, encoding=None, layout_engine=None)A copy with another size, index, encoding or layout_engine; the same file.
get_variation_axes()The axes of a variable font, each with minimum, default and maximum. OSError for non-variable fonts.
get_variation_names()The named styles of a variable font, as bytes (b"Bold").
getbbox(text, mode='', direction=None, features=None, language=None, stroke_width=0, anchor=None)The ink box (left, top, right, bottom) of the text relative to the anchor, including stroke_width.
getlength(text, mode='', direction=None, features=None, language=None)The advance width in pixels (float): where the next character would start. Use this to place text after text.
getmask(text, mode='', direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, start=None)Renders the text into a core image (the glyph coverage mask), without offset.
getmask2(text, mode='', direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, start=None, *args, **kwargs)Like getmask(), and also returns the offset at which the mask must be placed.
getmetrics()(ascent, descent) in pixels: how far the font reaches above and below the baseline, for any text.
getname()(family, style), e.g. ('DejaVu Sans', 'Book').
set_variation_by_axes(axes)Sets a variable font's axes, one value per axis in the order of get_variation_axes().
set_variation_by_name(name)Selects a named style of a variable font, e.g. b"Bold".

ImageText.Text methods 5

Name and signatureWhat it does
embed_color()Draw colour glyphs (emoji fonts) in their own colours; needs an RGB or RGBA image.
get_bbox(xy=(0, 0), anchor=None, align='left')The ink box of the (possibly multiline) text, with stroke, for a given xy, anchor and align.
get_length()The advance width of single-line text. Raises ValueError for multiline text.
stroke(width=0, fill=None)Sets an outline: width in pixels and its fill colour.
wrap(width, height=None, scaling=None)Inserts line breaks so the text fits width; with height, returns what did not fit as a new Text; with scaling="shrink" or "grow" (or (mode, limit)) changes the font size to fill the box. Added in Pillow 12.2.

Sources

What this page shows comes from running its code with Pillow 13.0.0. The API details and version history were checked against these primary sources:

The outputs and images on this page are the real results of running every example with Pillow 13.0.0 on Python 3.13 (Linux) on 2026-10-29. Every example is also re-run automatically on macOS (Darwin 25.6.0, Pillow 12.3.0), Linux (Linux 6.17.0-1022-azure, Pillow 12.3.0), Windows (Windows 2025Server, Pillow 12.3.0); the line under each example shows the result per operating system. The DejaVu Sans font files sit next to each script so font examples behave the same everywhere. Sample photos: NASA/Sam Lott, public domain. Spotted something wrong? Tell us.