Python pillow/PIL无法识别对象“imagedraw”的属性“textsize”

eiee3dmh  于 3个月前  发布在  Python
关注(0)|答案(3)|浏览(5935)

我已经在我的环境中检查了python版本(sublime text),它是3.11.0,最新的,我检查了pillow版本,它是10.0.0,最新的,我的代码看起来与其他在线示例相似。
代码有一部分是意大利语,但它很容易理解。
问题出在“disegno.textsize(testo,font=font)”
在我运行代码之后:

line 14, in metti_testo_su_sfondo
    text_width, text_height = disegno.textsize(testo, font=font)
                              ^^^^^^^^^^^^^^^^
AttributeError: 'ImageDraw' object has no attribute 'textsize'

字符串
这很奇怪,因为imagedraw应该有textsize属性。我是一个新手,我希望我没有错过任何明显的东西

from PIL import Image, ImageDraw, ImageFont

def metti_testo_su_sfondo(testo, sfondo, posizione=(10, 10), colore_testo=(0, 0, 0), dimensione_font=25):
# Apri l'immagine dello sfondo
immagine_sfondo = Image.open(sfondo)

disegno = ImageDraw.Draw(immagine_sfondo)

font = ImageFont.truetype("ARIAL.TTF", dimensione_font)

text_width, text_height = disegno.textsize(testo, font=font)

# Calcola le coordinate del testo centrato
x = (immagine_sfondo.width - text_width) // 2
y = (immagine_sfondo.height - text_height) // 2

disegno.text((x, y), testo, fill=colore_testo, font=font)

immagine_sfondo.save("spotted.png")

testo_da_inserire = "Ciao, mondo!"
sfondo_da_utilizzare = "spotted_bianco.jpg" 

metti_testo_su_sfondo(testo_da_inserire, sfondo_da_utilizzare)


目标是一个代码,使我的图像自动,而不需要手动编辑它们。我检查了构建系统,Python版本和枕头版本。当我通过CMD运行代码时,它给了我这个错误:

from PIL import Image, ImageDraw, ImageFont
ModuleNotFoundError: No module named 'PIL'

qltillow

qltillow1#

textsize被弃用,正确的属性是textlength,它给你文本的宽度。对于高度,使用fontsize * 你写了多少行文本。

wfsdck30

wfsdck302#

它不再被称为textsize,它被称为textlength

pb3s4cty

pb3s4cty3#

正如其他答案所提到的,textsize已被弃用。没有textheight,但您可以使用textlength
如果你只是想要一个可以测试给定的textfont对的函数,你可以用textbbox做这样的事情:

def textsize(text, font):
    im = Image.new(mode="P", size=(0, 0))
    draw = ImageDraw.Draw(im)
    _, _, width, height = draw.textbbox((0, 0), text=text, font=font)
    return width, height

字符串
应该是一样的

相关问题