Pillow ImageDraw textbbox() Method
textbbox()The method isImageDrawa very practical feature in the module, used to calculate the bounding box occupied by the given text when drawn on an image.
textbbox()The method does not actually draw the text, but returns the coordinates of the rectangular area the text will occupy.
Method Syntax
textbbox(xy, text, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None, stroke_width=0)
Parameter Details
1. xy (Required)
- Type: tuple (x, y)
- Description: Specifies the starting coordinate position of the text
- Note: The actual text position is also affected by the
anchorparameter.
2. text (Required)
- Type: string
- Description: The text content for which the bounding box needs to be calculated
3. font (Optional)
- Type:
ImageFont: object - Default value: None (uses default font)
- Description: Specifies the font used for the text
4. anchor (Optional)
- Type: string
- Default value: None (equivalent to "la")
- Description: Controls the alignment of the text relative to the xy coordinates
- Common values:
- "la": left-aligned, baseline-aligned (default)
- "lt": left-aligned, top-aligned
- "ma": center-aligned, baseline-aligned
- "mm": fully centered (horizontal and vertical)
5. spacing (Optional)
- Type: integer
- Default value: 4
- Description: Line spacing for multi-line text
6. align (Optional)
- Type: string
- Default value: "left"
- Description: Alignment of multi-line text ("left", "center", "right")
7-10. Other Advanced Parameters
direction,features,language,stroke_widthParameters such as these control advanced features of text rendering; beginners usually do not need to master them immediately.
Return Value
textbboxThe method returns a 4-tuple(left, top, right, bottom), representing the bounding box coordinates of the text.
Practical Application Examples
Example 1: Basic Usage
Example
# Create a blank image
image = Image.new('RGB', (400, 200), 'white')
draw = ImageDraw.Draw(image)
# Load font
font = ImageFont.truetype('arial.ttf', 24)
# Calculate text bounding box
bbox = draw.textbbox((50, 50), "Hello Pillow!", font=font)
print("Text bounding box:", bbox) # Output: (left, top, right, bottom)
# Draw bounding box (visualization)
draw.rectangle(bbox, outline='red')
# Actually draw the text
draw.text((50, 50), "Hello Pillow!", font=font, fill='black')
image.show()
Example 2: Using the anchor Parameter
Example
# Center point coordinates
center_x, center_y = 200, 100
# Calculate the center-aligned text bounding box
bbox = draw.textbbox((center_x, center_y), "Centered", font=font, anchor="mm")
print("Center-aligned bounding box:", bbox)
# Draw center point and bounding box
draw.rectangle(bbox, outline='blue')
draw.ellipse([(center_x-2, center_y-2), (center_x+2, center_y+2)], fill='green')
# Draw text
draw.text((center_x, center_y), "Centered", font=font, fill='black', anchor="mm")
image.show()
Common Application Scenarios
- Text layout calculation: Determine the space it occupies before drawing text
- Automatic line wrapping: Calculate how text wraps based on available width
- Text centering: Achieve precise centering by combining bounding box calculations
- Collision detection: Avoid text overlapping with other elements
Notes
- Font impact: Different fonts may return very different bounding box sizes
- Multi-line text: For multi-line text, the bounding box includes the area of all lines
- Performance considerations: Frequent calls may affect performance; it is recommended to cache results
- Accuracy: The bounding box calculation is approximate; actual rendering may differ slightly
Comparison with textsize
In older versions of Pillow, the commonly usedtextsizemethod to obtain text size, but this method has been deprecated.textbboxIt provides more precise information (including not only width and height but also position information), making it the preferred method for new code.
Example
width, height = draw.textsize("Text", font=font)
# New method (recommended)
left, top, right, bottom = draw.textbbox((0, 0), "Text", font=font)
width = right - left
height = bottom - top
Summary
ImageDraw.textbboxThe method is a powerful and practical tool in the Pillow library, especially suitable for scenarios that require precise control of text layout. By understanding its parameters and return values, developers can easily implement various complex text layout requirements.