我尝试使用 Python PIL 在图像上绘制字符。对于 ImageDraw.Draw.text() 函数,xy 参数指向文本的左上角。但是我将 xy 设置为 (0,0),角色还没有绘制在图像的左上角。
from PIL import ImageFont, ImageDraw, Image
imageSize=(40,40)
mage = Image.new("RGB", imageSize, (0,0,0))
draw = ImageDraw.Draw(image)
txt = "J"
font = ImageFont.truetype("ANTQUAB.ttf",35)
draw.text((0,0), txt, font=font)
为什么?
看起来有特定于字体的偏移量;您可以从 FreeTypeFont.getbbox() 返回的“顶部”值获取垂直偏移。从 draw.text 调用中的 y 坐标中减去此偏移量将使文本顶部与图像顶部对齐。
from PIL import ImageFont, ImageDraw, Image
text = 'J'
font = "arial.ttf"
fontsize = 12
img_w = 100
img_h = 100
canvas = Image.new('RGBA', size=(img_w,img_h), color='white')
draw = ImageDraw.Draw(canvas)
y_text = 0
font_obj = ImageFont.truetype(font, fontsize)
(left, top, right, bottom) = font_obj.getbbox(text)
x_pos = 0
y_pos = 0
# offset the y coordinate in the draw call by the "top" parameter fromgetbbox; this is the font-specific text padding
draw.text(xy=(x_pos, y_pos-top),
text=text,
font=font_obj,
align='left',
fill='black')
canvas.show()
此代码:
from PIL import ImageFont, ImageDraw, Image
imageSize=(100,100)
image = Image.new("RGB", imageSize, (0,0,0))
draw = ImageDraw.Draw(image)
txt = "J"
font = ImageFont.truetype("ARIAL.ttf",35)
draw.text((0,0), txt, font=font)
image.show()
生成这个:
这不是你所期待的吗?