python - 枕头,文本居中不起作用,这是如何实现的?

标签 python python-imaging-library photoshop

我已经测试了计算并且数学是正确的(并考虑了字体的高度和宽度),但是在 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% 的上边距。我可以解释这一点,但这似乎很奇怪。

最佳答案

我没有方便测试的确切字体,但这可能是因为 Pillow 的 textsizetext 方法默认锚定到上升高度而不是实际呈现的顶部;见this note在文档中。尝试使用 textbbox而不是 textsize,并指定 top anchor在那个和 text 方法中,看看它的行为是否更直观。

请注意,您可能只将文本锚定到 'mm',中间/中间,以根据图像中点的坐标将其居中。不过,这会垂直锚定在升部和降部之间的中间位置,因此它实际上可能看起来并不居中,具体取决于字体和您呈现的字形。

关于python - 枕头,文本居中不起作用,这是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65524280/

相关文章:

Javascript 以不同大小调整图像大小,其中只有宽度很重要

android - 如何创建最高质量的 Android 按钮?

python - Pyinotify 不与 pygtk 一起运行

python - 如果 slug 已经存在于 postgresql 数据库中,则跳过保存行 - python

python 枕头 : how to produce 3-channel image from 1-channel image?

Python PIL Crop 不裁剪图像

java - 如何在Java中读取PSB文件扩展名(图像-Photoshop)?

python - 需要使用现有数组生成新数组

python - 如何将圆形标记添加到嵌入在 QWebEngineView 中的渲染叶图?

python - OpenCV 中的 PIL ImageChops.screen