枕头,如何将文本放在图像的中心

问题描述 投票:5回答:1

我使用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')

Here is the output:

enter image description here

Question:

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

python python-3.x python-imaging-library
1个回答
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

0.21因子通常适用于相同字体的大范围字体。例如。只需插入字体大小30:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.