繁体   English   中英

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 ,它会返回最终文本将具有的宽度和高度 - draw.textsize起,您只需计算左上角呈现文本的位置,如下所示:

顶部将是您的 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包括一个可选的“锚”的说法-但它可能值不记录,也不是文档状态,无论是实际实现如果实现了,并且有代表(horizo​​ntal_center,底部的值。 ) 作为 Anchor,您应该只需要传递 image_width / 2 和 image_height,而无需调用draw.textsize )

所需变量的名称REQ_WIDTHREQ_HEIGHT有点误导,因为它们不是宽度和高度。

你只需要做一点数学:

    X_POS = h - text_h
    Y_POS = w//2 - text_w//2  # or (w - text_w) // 2

    draw.text((X_POS, Y_POS), title, (255,255,255), font=font)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM