Centralize text in image outputs error

时光总嘲笑我的痴心妄想 提交于 2019-12-25 17:13:25

问题


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:


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.



来源:https://stackoverflow.com/questions/48196186/centralize-text-in-image-outputs-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!