PIL:在图像的底部中间添加一个文本

PIL: add a text at the bottom middle of image

我有图片的宽度和高度。

img = Image.open(img_src)
width, height = img.size

font = ImageFont.truetype("MuseoSansCyrl_0.otf", 100)
text_w, text_h = draw.textsize(title, font)

我正在尝试寻找一种通用方法来在底部中间的图像中添加文本。

这是我写的函数:

def process_img(img_src, title, background):

    img = Image.open(img_src, 'r')
    draw = ImageDraw.Draw(img)
    w, h = img.size

    font = ImageFont.truetype("MuseoSansCyrl_0.otf", 100)
    text_w, text_h = draw.textsize(title, font)

    draw.text((REQ_WIDTH, REQ_HEIGHT), title, (255,255,255), font=font)

    img.save(img_src)

    return img_src

有什么方法可以得到 REQ_WIDTH 和 REQ_HEIGHT 吗?

您已经调用了 draw.textsize,returns 最终文本将具有的宽度和高度 - 从那时起,您只需计算左上角所在的位置像这样呈现您的文本:

顶部是您的 image_height - text_height,左侧是您的 image_width/2 - text_width / 2 - 因此,您的渲染调用变得简单:

draw.text(((w - text_w) // 2, h - text_h), title, (255,255,255), font=font)

(请注意,draw.text 包含一个可选的“锚”参数 - 但它的可能值没有记录,文档也没有说明它是否实际实现。如果它 实现了,并且有一个值表示 (horizontal_center, bottom) 作为 Anchor,你应该只需要传递 image_width / 2 和 image_height,而不需要呼叫 draw.textsize)

你为所需变量取的名字——REQ_WIDTHREQ_HEIGHT——有点误导,因为它们不是宽度和高度,它们是“xy 默认情况下相对于其左上角的文本锚点坐标 — 参见 documentation — 换句话说,它的位置。

你只需要做一点数学运算:

    X_POSN = h - text_h
    Y_POSN = w//2 - text_w//2  # Or (w - text_w) // 2

    draw.text((X_POSN, Y_POSN), title, (255,255,255), font=font)