Pillow ImageDraw.Draw.textsize 抛出“str”对象没有属性“getsize”

问题描述 投票:0回答:2

在 Pillow 中,我试图获取文本的大小,以便知道如何将其放置在图像中。当尝试执行以下操作时,在调用 d.textsize(text, font=font_mono) 时,我不断收到错误“AttributeError: 'str' object has no attribute 'getsize'”。

我做错了什么?

from PIL import Image, ImageDraw

txt_img = Image.new("RGBA", (320, 240), (255,255,255,0))  # make a blank image for the text, initialized to transparent text color
d = ImageDraw.Draw(txt_img)
text = "abcabc"
font_mono="Pillow/Tests/fonts/FreeMono.ttf"
font_color_green = (0,255,0,255)
txt_width, _ = d.textsize(text, font=font_mono)
python python-imaging-library
2个回答
5
投票

font
需要是一个
ImageFont
对象:

from PIL import Image, ImageDraw, ImageFont

txt_img = Image.new("RGBA", (320, 240), (255,255,255,0))
d = ImageDraw.Draw(txt_img)
text = "abcabc"
font_mono="Pillow/Tests/fonts/FreeMono.ttf"
font_color_green = (0,255,0,255)
font = ImageFont.truetype(font_mono, 28)
txt_width, _ = d.textsize(text, font=font)

0
投票

我使用以下代码获取了文本的宽度和高度,它适用于现代版本的枕头

from PIL import ImageFont, ImageDraw, Image

image = Image.open("certificate.png")  
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("poppins_black.ttf", 100)
username = f"{first_name} {last_name}"
text_width, text_height = font.getlength(username), 100
© www.soinside.com 2019 - 2024. All rights reserved.