python - 由于 textsize 弃用,尝试使用 Python PIL ImageDraw.textbbox 但出现错误

标签 python python-imaging-library

我用 textsize 编写文本时遇到零问题,但我不明白我用 textbbox 做错了什么。我收到错误:

File "c:\Users\email\OneDrive\Personal\Documents\Code\Python\TestPatternGenerator\test.py", line 14, in textwidth, textheight = draw.textbbox("text", font=font) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: ImageDraw.textbbox() missing 1 required positional argument: 'text'

from PIL import Image, ImageDraw, ImageFont

# Create an image object
img = Image.new("RGB", (400, 400), (255, 255, 255))

# Create a draw object
draw = ImageDraw.Draw(img)

# Define the font to be used for the text
font = ImageFont.truetype("arial.ttf", 36)

# Get the text bounding box
text = "Hello World!"
textwidth, textheight = draw.textbbox(text, font=font)

# Calculate the position for the text
x = (img.width - textwidth) / 2
y = (img.height - textheight) / 2

# Draw the text on the image
draw.text((x, y), text, (0, 0, 0), font=font)

# Save the image
img.save("hello_world.png")

最佳答案

错误消息表明您在此行中缺少参数:

textwidth, textheight = draw.textbbox(text, font=font)

如果您查找 documentation for textbbox ,您会看到第一个参数应该是 xy,即文本的 anchor 坐标。您的代码行中缺少此内容。

解决方案:您应该首先计算位置,然后在调用 bbox 时使用该位置。或者,在您的情况下,您只想知道代码该点处的边界框的大小,因此您可以使用 (0, 0) 作为位置。

关于python - 由于 textsize 弃用,尝试使用 Python PIL ImageDraw.textbbox 但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75344148/

相关文章:

python - 以多节点方式获取分布式 Tensorflow 中使用的 GPU 数量

python - 进行反向传播和梯度下降时,numpy 数组和矩阵出现问题

python - 将 celery 与 django 应用程序和后端服务器一起使用

python - 如何将函数应用于 numpy 数组中的每个第三轴元素?

python - 如何从 Python 中的 URL 读取图像数据?

python - 有没有办法从单词中正确删除时态或复数?

Python 在 IDLE 中重启 shell

python - 通过curl向Flask提交图像失败,错误代码为 "not enough image data'

python - 从 numpy 数组转换为图像时获得意外的颜色输出

python - 如何将图像传递给 Django 中的模板?