Centralize text in image outputs error

2019-09-20 04:05发布

Below code is not centralizing text no error in code, but i want to centralize text.

import os
unicode_text = u"\u0627\u0628\u067E"
list_of_letters = list (unicode_text) 

        char = u''.join(word) 
        t1 = arabic_reshaper.reshape(char) 
        W,H= (32, 32)
        img= PIL.Image.new('RGBA', (W, H), (255, 255, 255),)
        draw = PIL.ImageDraw.Draw(img)   
        font = PIL.ImageFont.truetype( r"C:\Downloads\arabic.ttf", 15)
        t2 = get_display(t1) 
        w, h = draw.textsize(t2.encode('utf-8'))
        draw.text(((W-w)/2,(H-h)/2), t2, fill="#000000", font=font)

1条回答
Luminary・发光体
2楼-- · 2019-09-20 04:23

Your code does not center correctly because it does not retrieve the actual character width and height. You can see that if you print out the character sizes that textsize returns and then change the font size. You still get the same character sizes!

Why does it not change? Because you load a font but then don't use it for measuring. If you set it inside the draw object, or add font=font to both draw.textsize and draw.text, it works as expected.

(Just doing that gives an error on the original textsize line; possibly you attempted to fix the issue in an unrelated way by adding .encode('utf8). But that is not necessary.)

draw = PIL.ImageDraw.Draw(img)
draw.font = PIL.ImageFont.truetype( "times.ttf", 48)
t2 = get_display(t1) 
w, h = draw.textsize(t2)
draw.text(((W-w)/2,(H-h)/2), t2, fill="#000000")
print ("char: %04X w %d h %d" % (ord(char),w,h))

This results in correctly centered characters throughout, the same for both Latin and Arabic letters.

centered colon centered capital I centered isolated teh centered isolated hah

查看更多
登录 后发表回答