我需要计算使用自定义字体呈现大量字符串时的长度。从 shell 脚本和 ImageMagick,我可以使用 annotate 命令行选项做一些事情。
convert -debug annotate xc: -font "customfont.ttf" -pointsize "25" -annotate 0 "this is the text" out.png
然后读取渲染图像的宽度。
我正在努力了解如何使用 python 'Wand' 库执行此操作。我已经创建了一个字体对象,但我似乎需要定义 Canvas 的宽度来绘制字体。
任何建议表示赞赏。
最佳答案
与 wand您将使用 wand.drawing.Drawing.get_font_metrics
,它将返回 FontMetrics
类的实例。
例子
from wand.image import Image
from wand.drawing import Drawing
with Image(filename='wizard:') as img:
with Drawing() as context:
context.font_family = 'monospace'
context.font_size = 25
metrics = context.get_font_metrics(img,
"How BIG am I?",
multiline=False)
print(metrics)
#=> FontMetrics(character_width=25.0,
# character_height=25.0,
# ascender=23.0,
# descender=-5.0,
# text_width=170.0,
# text_height=29.0,
# maximum_horizontal_advance=50.0,
# x1=0.0,
# y1=0.0,
# x2=19.21875,
# y2=18.0,
# x=170.0,
# y=0.0)
关于python - 使用 Wand/ImageMagick Python 将文本字符串渲染为图像以计算长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32905448/