枕头,如何将文字放在图片的中央

时间:2019-04-20 13:24:32

标签: python python-3.x python-imaging-library

我使用Pillow(PIL)6.0,并在图像中添加文本。我想将文本放在图像的中心。这是我的代码,

import os
import string
from PIL import Image
from PIL import ImageFont, ImageDraw, ImageOps

width, height = 100, 100

text = 'H'
font_size = 100

os.makedirs('./{}'.format(text), exist_ok=True)

img = Image.new("L", (width, height), color=0)   # "L": (8-bit pixels, black and white)
font = ImageFont.truetype("arial.ttf", font_size)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(text, font=font)
draw.text(((width-w)/2, (height-h)/2), text=text, fill='white', font=font)

img.save('H.png')

以下是输出:

enter image description here

问题:

文本水平居中,但垂直居中。如何将其水平和垂直放置在中央?

1 个答案:

答案 0 :(得分:2)

文本始终在字符周围添加一些空格,例如如果我们创建的框与为您的“ H”报告的尺寸完全相同

img = Image.new("L", (width, height), color=0)   # "L": (8-bit pixels, black and white)
font = ImageFont.truetype("arial.ttf", font_size)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(text, font=font)
# draw.text(((width-w)/2, (height-h)/2), text=text, fill='white', font=font)
# img.save('H.png')
img2 = Image.new("L", (w, h), color=0)   # "L": (8-bit pixels, black and white)
draw2 = ImageDraw.Draw(img2)
draw2.text((0, 0)), text=text, fill='white', font=font)
img2.save('H.png')

给出边界框:

enter image description here

知道行高通常比字形/字符大20%(加上一些试验和错误),因此我们可以找出多余空间的程度。 (宽度的额外空间平均分配,因此居中不太有趣。)

draw2.text((0, 0 - int(h*0.21)), text=text, fill='white', font=font)

将“ H”移到顶部:

enter image description here

将其重新添加到您的原始代码中:

img = Image.new("L", (width, height), color=0)   # "L": (8-bit pixels, black and white)
font = ImageFont.truetype("arial.ttf", font_size)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(text, font=font)
h += int(h*0.21)
draw.text(((width-w)/2, (height-h)/2), text=text, fill='white', font=font)
img.save('H.png')

给予:

enter image description here

对于{em>相同字体,0.21因素通常适用于较大的字体大小。例如。只需插入30号字体:

enter image description here