我正在设置一个程序在图像上写一些数字。字体大小将根据其写入位置而变化(此大小将被硬编码)。
阅读文档后,我正在使用ImageFont.truetype('font.ttf', fontSize)
加载字体fontSize = 400
。
from PIL import Image, ImageDraw, ImageFont
image = Image.open('base.jpg')
draw = ImageDraw.Draw(image);
fontSize = 400
font = ImageFont.truetype('font.ttf', fontSize)
color = 'rgb(0, 0, 0)'
def drawInfo():
draw.text((50, 200), '20', fill=color, font=font)
image.save('newVersion.jpg')
drawInfo()
字体:https://fonts.google.com/specimen/Kalam?selection.family = Kalam
base.jpg
:https : //ibb.co/6XQbxHv
newVersion.jpg
:https://ibb.co/7XFRTyg
预期的结果是,20
强度不足时,左上角的小部分将很大(字体大小为400)。不幸的是,它似乎只是默认大小。我究竟做错了什么?
简短的答案是400太大了,但是如果您想知道为什么它会导致字体变成默认大小,我将带您轻松进行一下。
首先,在代码中使用font = ImageFont.truetype('font.ttf', 400)
。这会将truetype
功能部署在ImageFont库中,该库调用FreeTypeFont
:
def freetype(font):
return FreeTypeFont(font, size, index, encoding, layout_engine)
try:
return freetype(font)
except IOError:
有趣的部分是中发生了什么FreeTypeFont
,如下所示:
FreeTypeFont调用core.getfont,它实际上使用_imagingft.c库,这是400的字体杀死_imagingft getfont函数的地方,该函数放弃了加载文本并抛出错误:
最后,如果您还记得第一个函数,truetype
它实际上有一个try: except IOError:
,导致它调用不带字体大小的FreeTypeFont
函数,使其默认为10,从而导致当前问题:
本质上,解决方案是尝试使用不会破坏_imagingft库的最大字体大小,或利用其他库来加载字体。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句