Search code examples
pythonpython-imaging-library

Pillow ImageDraw.Draw.textsize throws 'str' object has no attribute 'getsize'


In Pillow, I'm trying to get the size of a text so I could know how to place it in the image. When trying to do the following, I keep getting the error "AttributeError: 'str' object has no attribute 'getsize'" when calling d.textsize(text, font=font_mono).

What am I doing wrong?

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)

Solution

  • The font needs to be an ImageFont object:

    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)