Pillow中心对齐文本无效,如何实现?

3

我已经测试了计算,数学是正确的(并考虑了字体的高度和宽度),但在Python创建图像并将其放入Photoshop后,文本的垂直和水平居中对齐不正确。请问我应该用我的代码做些什么别的吗?

from PIL import Image, ImageDraw, ImageFont

# base = Image.open("Images/Phones/KK17018_Navy_KH10089.jpg").convert("RGBA")
base = Image.open('Images/Tablets/KK17076_Hunter_KH235.jpg').convert('RGB')

# Create blank rectangle to write on
draw = ImageDraw.Draw(base)

message = 'GGS'
num1, num2 = base.size
bounding_box = [0, 0, num1, num2]
x1, y1, x2, y2 = bounding_box  # For easy reading

# font = ImageFont.truetype('Fonts/Circle/Circle Monograms Three White.ttf', size=413)


font = ImageFont.truetype('Fonts/Modern/Vhiena_Monoline.otf', size=800)
font2 = ImageFont.truetype('Fonts/Modern/Vhiena_Base.otf', size=800)
font3 = ImageFont.truetype('Fonts/Modern/Vhiena_Extrude A.otf', size=800)

# Calculate the width and height of the text to be drawn, given font size
w, h = draw.textsize(message, font=font3)


# Calculate the mid points and offset by the upper left corner of the bounding box
x = (x2 - x1 - w) / 2 + x1
y = (y2 - y1 - h) / 2 + y1

# Write the text to the image, where (x,y) is the top left corner of the text

draw.text((x, y), message, align='center', font=font3, fill='orange')
draw.text((x, y), message, align='center', font=font2, fill='black')
draw.text((x, y), message, align='center', font=font, fill='white')

# Draw the bounding box to show that this works
# draw.rectangle([x1, y1, x2, y2])

base.show()
base.save('test_image.jpg')

文本的左上角 x、y 坐标应为 (874,1399.5),但在 Photoshop 中显示为 (875,1586)。以上 Python 代码确实正确计算了 (874,1399.5),但某些内容使字体低于其应有的位置。

此外,我将字体堆叠在一起,因为它可以提供一个普通字体,一个阴影字体和一个让字体中间看起来是斜切的字体。是否有更好的方法,或者堆叠字体是可行的做法?

编辑:经过进一步测试,随着字体大小的增加,有些内容会给字体添加 22% 的顶部边距。我可以解决这个问题,但这似乎很奇怪。


1
两天前有一个关于居中文本的问题 - 在我的回答中,我展示了一些图像,这些图像显示了textsize和texbbox之间的区别。 - furas
1个回答

2
我没有您所需的确切字体进行测试,但这可能是因为Pillow的textsizetext方法默认锚定到上升高度而不是实际渲染的顶部;请参见文档中的此注释。尝试使用textbbox代替textsize,并在两个方法中都指定顶部锚点,看看是否更直观地表现。
请注意,您可能可以将文本锚定到'mm',即中/中心,以基于图像中点的坐标居中。然而,这会垂直地将锚点固定在上升和下降之间的一半,因此根据字体和渲染的字形,它可能并不真正居中。

2
我一直成功地使用anchor="mm",但最近出了问题。结果发现我拿起这个我有段时间没有打过交道的代码,并在Python 2中运行它(它在Python 3上工作)。我不知道这是否是Pillow / PIL的版本问题,但还是要注意一下。 - Filipe Nicoli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接