Reputation: 431
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)
Upvotes: 3
Views: 16140
Reputation: 34
I got the width and height of the text using following code and it works for the modern version of the pillow
from PIL import ImageFont, ImageDraw, Image
image = Image.open("certificate.png")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("poppins_black.ttf", 100)
username = f"{first_name} {last_name}"
text_width, text_height = font.getlength(username), 100
Upvotes: -1
Reputation: 71580
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)
Upvotes: 4