gpt4 book ai didi

Python图片库——字体定位

转载 作者:太空狗 更新时间:2023-10-29 23:58:13 25 4
gpt4 key购买 nike

编辑:添加了完整的工作示例

我有以下程序:

from PIL import Image, ImageDraw, ImageFont

FULL_SIZE = 50
filename = 'font_test.png'
font="/usr/share/fonts/truetype/msttcorefonts/arial.ttf"
text="5"

image = Image.new("RGBA", (FULL_SIZE, FULL_SIZE), color="grey")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font, 40)
font_width, font_height = font.getsize(text)
draw.rectangle(((0, 0), (font_width, font_height)), fill="black")
draw.text((0, 0), text, font=font, fill="red")
image.save(filename, "PNG")

这会生成以下图像:

enter image description here

似乎在编写文本 PIL 库时会在顶部添加一些边距。这个边距取决于我使用的字体。

在尝试定位文本时如何考虑这一点(我希望它位于矩形的中间)?

(在 Ubuntu 14.04 上使用 Python 2.7.6 和 Pillow 2.3.0)

最佳答案

我不明白为什么,但是从 y 坐标中减去 font.getoffset(text)[1] 可以在我的电脑上修复它。

from PIL import Image, ImageDraw, ImageFont

FULL_SIZE = 100
filename = 'font_posn_test.png'
fontname = '/usr/share/fonts/truetype/msttcorefonts/arial.ttf'
textsize = 40
text = "5"

image = Image.new("RGBA", (FULL_SIZE, FULL_SIZE))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(fontname, textsize)
print font.getoffset(text)
print font.font.getsize(text)
font_width, font_height = font.getsize(text)

font_y_offset = font.getoffset(text)[1] # <<<< MAGIC!

draw.rectangle(((0, 0), (font_width, font_height)), fill="black")
draw.text((0, 0 - font_y_offset), text, font=font, fill="red")
image.save(filename, "PNG")

关于Python图片库——字体定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com