如何获取在图片上由 Image.Draw 绘制的文本的宽度和高度? [英] How can I get the width and height of a text that was Image.Draw-drawn on a picture?

查看:53
本文介绍了如何获取在图片上由 Image.Draw 绘制的文本的宽度和高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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".

解决方案

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.

这篇关于如何获取在图片上由 Image.Draw 绘制的文本的宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆