Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

python - How can I get the width and height of a text that was Image.Draw-drawn on a picture?

enter image description hereThere are already a few questions, that sound quite similar to this one on stackoverflow, but their focuses are a little bit different from what I want to know.

I pasted a text on an image using ImageDraw from the Python Image Library. My question now is: Is there a way to find out the width and height of the text as a whole? For myself imagine the text to have kind of a rectangular frame. I want to get the measurements of this text-field. Can my text1 be treated like an image and can I get its size by typing in something like "width, height = text1.size"?

I have already tried to get the width, by using a ImageDraw.getwidth command, as proposed in other questions, but those solutions sadly didn't work for me.

What I want to achieve in particular is to be able to calculate, where the next text-field can be placed without overlaying the current text.

Thanks in advance for your support!

In the attached picture you can see the two ImageDraw-drawed texts, named "text" and "xyz". I want xyz to fit behind "test", even if "test" would include more letters. Therefor I need to know the width of "test".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can just write the same text with the same font of the same size in white on a separate canvas (black background) and then get the trimmed "bounding box" like this which is the size:

#!/usr/bin/env python3

from PIL  import Image, ImageFont, ImageDraw

# Create a blank canvas
canvas = Image.new('RGB', (100,100))

# Get a drawing context
fontsize=28
draw = ImageDraw.Draw(canvas)
monospace = ImageFont.truetype("/Library/Fonts/Andale Mono.ttf",fontsize)

text = "Hello"
white = (255,255,255)
draw.text((10, 10), text, font=monospace, fill=white)

# Find bounding box
bbox = canvas.getbbox()

# Debug
print(bbox)

Output

(12, 17, 93, 36)

That means the text is (93-12) = 81 pixels wide and (36-17) = 19 pixels tall.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...