Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pillow ImageDraw textbbox() Method

Pillow ImageDraw textbbox() Method

textbbox() The method is ImageDraw A very practical feature in the module, it is used to calculate the bounding box occupied by 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: Two-tuple (x, y)
  • Description: Specify the starting coordinate position of the text
  • Note: The actual text position is also affected by the anchor parameter

2. text (required)

  • Type: String
  • Description: The text content whose bounding box needs to be calculated

3. font (optional)

  • Type: ImageFont object
  • Default value: None (use the default font)
  • Description: Specify the font used by the text

4. anchor (optional)

  • Type: String
  • Default value: None (equivalent to "la")
  • Description: Control 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: The line spacing of multi-line text

6. align (optional)

  • Type: String
  • Default value: "left"
  • Description: The alignment of multi-line text ("left", "center", "right")

7-10. Other Advanced Parameters

  • direction, features, language, stroke_width and other parameters are used to control advanced features of text rendering, beginners usually do not need to master them immediately.

Return Value

textbbox The method returns a four-tuple (left, top, right, bottom), representing the bounding box coordinates of the text.


Practical Application Examples

Example 1: Basic usage

Example

from PIL import Image, ImageDraw, ImageFont

# Create a blank image
image = Image.new('RGB', (400, 200), 'white')
draw = ImageDraw.Draw(image)

# Load the font
font = ImageFont.truetype('arial.ttf', 24)

# Calculate the text bounding box
bbox = draw.textbbox((50, 50), "Hello Pillow!", font=font)

print("Text bounding box:", bbox)  # Output: (left, top, right, bottom)

# Draw the 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

# Continue using the image and draw objects above

# 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 the 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 the text
draw.text((center_x, center_y), "Centered", font=font, fill='black', anchor="mm")

image.show()

Common Application Scenarios

  1. Text Layout Calculation: Determine the space occupied by text before drawing it
  2. Automatic Line Wrapping: Calculate how text wraps based on available width
  3. Text Centering: Combine bounding box calculation to achieve precise centering
  4. Collision Detection: Avoid text overlapping with other elements

Notes

  1. Font Impact: The bounding box sizes returned by different fonts may vary greatly
  2. Multi-line Text: For multi-line text, the bounding box includes the area of all lines
  3. Performance considerations: Frequent calls may affect performance, it is recommended to cache the results
  4. Accuracy: Bounding box calculation is approximate, actual rendering may differ slightly

Comparison with textsize

In older versions of Pillow, people commonly used textsize method to get text size, but this method has been deprecated.textbbox provides more accurate information (not only width and height, but also position information), and is the preferred method for new code.

Example

# Old method (not recommended)
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.textbbox The 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 achieve various complex text layout needs.