Pillow: TypeError: expected string [draw.textsize(font)]

Created on 18 Sep 2016  路  3Comments  路  Source: python-pillow/Pillow

That piece of code:

W, H = (1285,720)
text = "Hello world"
img = Image.open("img.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/usr/share/fonts/MyriadProCondBold.ttf", 90)
w, h = draw.textsize(text.encode('utf-8'), font=font)
draw.text(((W-w)/2,520),text,(255,255,255),font=font)

Output:

w, h = draw.textsize(text.encode('utf-8'), font=font)
  File "/usr/lib/python3.5/site-packages/PIL/ImageDraw.py", line 273, in textsize
    return font.getsize(text)
  File "/usr/lib/python3.5/site-packages/PIL/ImageFont.py", line 141, in getsize
    size, offset = self.font.getsize(text)
TypeError: expected string

Most helpful comment

Just as an explanation of what's happening - you are passing in bytes when it 'expected string'. If you change text.encode('utf-8') to just text, you should find that the code runs without a problem.

All 3 comments

Just as an explanation of what's happening - you are passing in bytes when it 'expected string'. If you change text.encode('utf-8') to just text, you should find that the code runs without a problem.

Thanks for the thumbs up response. If you feel like that resolves your situation, please close this issue.

@radarhere thanks for the help. You've been very much helped me. Issue has been resolved!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FlowerCode picture FlowerCode  路  4Comments

hxzhao527 picture hxzhao527  路  4Comments

thinrhino picture thinrhino  路  3Comments

etc0de picture etc0de  路  4Comments

readyready15728 picture readyready15728  路  4Comments