python-pillow / Pillow

Python Imaging Library (Fork)
https://python-pillow.org
Other
12.26k stars 2.23k forks source link

How to obtain the rectangular coordinates of each character #8537

Closed monkeycc closed 4 hours ago

monkeycc commented 6 hours ago

微信截图_20241106111719

Generate text images How to obtain the rectangular coordinates of each character

from PIL import Image, ImageDraw, ImageFont

# Load font
font = ImageFont.truetype("Tests/fonts/FreeMono.ttf", size=20)

# Create image
im = Image.new("RGB", (200, 100), color=(255, 255, 255))  # White background
draw = ImageDraw.Draw(im)

# Text to draw
text = "Hello world"

# Calculate text size and bounding box
left, top, right, bottom = draw.textbbox((0, 0), text, font)
width, height = right - left, bottom - top

# Draw text
draw.text((10, 10), text, font=font, fill=(0, 0, 0))  # Black text

# Draw rectangle around text

# Show the image
im.show()

draw.textbbox can only retrieve the length of the entire string

radarhere commented 4 hours ago

Hi. I suggest looking at https://stackoverflow.com/a/70636273/4093019

Essentially,

from PIL import Image, ImageDraw, ImageFont
image = Image.new("RGB", (200, 80))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("arial.ttf", 30)

xy = (20, 20)
text = "Example"
draw.text(xy, text, font=font)

x, y = xy
for c in text:
  bbox = draw.textbbox((x, y), c, font=font)
  draw.rectangle(bbox, outline="red")
  x += draw.textlength(c, font=font)
monkeycc commented 4 hours ago

wow Thanks for your help The problem has been resolved