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)
1

1 Answer

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest