Search code examples
pythonpython-3.xpython-imaging-library

Python pillow/PIL doesn't recognize the attribute "textsize" of the object "imagedraw"


I already checked python version on my environment (sublime text) and it is 3.11.0, the latest, I checked pillow version which is 10.0.0, the latest, and my code looks similar to other examples online.

the code has a part in Italian, but its pretty understandable.

the problem is at "disegno.textsize(testo, font=font)

after I run the code:

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

its strange because imagedraw should have the textsize attribute. I'm a novice, I hope I didn't miss anything blatant


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)

The objective is a code that makes me images automatically without needing to edit them manually. I checked build system, python version and pillow version. when I run the code through cmd though it gives me this error:

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

Solution

  • textsize was deprecated, the correct attribute is textlength which gives you the width of the text. for the height use the fontsize * how many rows of text you wrote.