我使用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')
文本水平居中,但垂直居中。如何将其水平和垂直放置在中央?
答案 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')
给出边界框:
知道行高通常比字形/字符大20%(加上一些试验和错误),因此我们可以找出多余空间的程度。 (宽度的额外空间平均分配,因此居中不太有趣。)
draw2.text((0, 0 - int(h*0.21)), text=text, fill='white', font=font)
将“ 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)
h += int(h*0.21)
draw.text(((width-w)/2, (height-h)/2), text=text, fill='white', font=font)
img.save('H.png')
给予:
对于{em>相同字体,0.21
因素通常适用于较大的字体大小。例如。只需插入30号字体: