Centralize Text In Image Outputs Error
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)
Solution 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
anddraw.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.
Post a Comment for "Centralize Text In Image Outputs Error"