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

eiee3dmh  于 2024-01-10  发布在  Python
关注(0)|答案(3)|浏览(9962)

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

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

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

  1. from PIL import Image, ImageDraw, ImageFont
  2. def metti_testo_su_sfondo(testo, sfondo, posizione=(10, 10), colore_testo=(0, 0, 0), dimensione_font=25):
  3. # Apri l'immagine dello sfondo
  4. immagine_sfondo = Image.open(sfondo)
  5. disegno = ImageDraw.Draw(immagine_sfondo)
  6. font = ImageFont.truetype("ARIAL.TTF", dimensione_font)
  7. text_width, text_height = disegno.textsize(testo, font=font)
  8. # Calcola le coordinate del testo centrato
  9. x = (immagine_sfondo.width - text_width) // 2
  10. y = (immagine_sfondo.height - text_height) // 2
  11. disegno.text((x, y), testo, fill=colore_testo, font=font)
  12. immagine_sfondo.save("spotted.png")
  13. testo_da_inserire = "Ciao, mondo!"
  14. sfondo_da_utilizzare = "spotted_bianco.jpg"
  15. metti_testo_su_sfondo(testo_da_inserire, sfondo_da_utilizzare)


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

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

qltillow

qltillow1#

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

wfsdck30

wfsdck302#

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

pb3s4cty

pb3s4cty3#

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

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

字符串
应该是一样的

相关问题