Python,以PIL为中心

时间:2017-07-10 05:16:08

标签: python text unicode python-imaging-library

我正在尝试使用PIL绘制单个大字符,但并非所有字符都具有相同的宽度,例如:“M”比“I”宽,我希望它们居中/对齐。我查看了draw.gettext和draw.getsize,并考虑了画布的宽度无济于事。

到目前为止,这是我的代码。

font_size=160
width = 200
height = 200
unicode_text = u"\u2104"
im  =  Image.new ( "RGB", (width,height), 'white' )
draw  =  ImageDraw.Draw (im)
unicode_font = ImageFont.truetype("DejaVuSans.ttf", font_size)
draw.text ((0,0), unicode_text, font=unicode_font, fill='black')
im.save("text.jpg")

1 个答案:

答案 0 :(得分:0)

你现在可能已经为自己解决了这个问题。您需要了解的是draw.textsize的可用性。

>>> from PIL import Image, ImageDraw
>>> from PIL import ImageDraw
>>> from PIL import ImageFont
>>> unicode_text = u"\u2104"
>>> im  =  Image.new ( "RGB", (200,200), 'white' )
>>> draw = ImageDraw.Draw(im)
>>> unicode_font = ImageFont.truetype("DejaVuSans.ttf", 160)
>>> text_width, text_height = draw.textsize(unicode_text, font=unicode_font)
>>> draw.text(((200-text_width)//2,(200-text_height)//2), unicode_text, font=unicode_font, fill='black')
>>> im.save('it.png')