python - PIL : add a text at the bottom middle of image

标签 python image image-processing fonts python-imaging-library

我有图像的宽度和高度。

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,它会返回最终文本的宽度和高度 - 从那时起,您只需计算左上角的位置像这样呈现您的文本:

顶部将是您的 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 包含一个可选的“anchor”参数 - 但它的可能值没有记录,文档也没有说明它是否实际实现。如果它 已实现,并且有一个值表示 (horizo​​ntal_center, bottom) 作为 Anchor,你应该只需要传递 image_width/2 和 image_height,而不需要调用 draw.textsize)

关于python - PIL : add a text at the bottom middle of image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37924130/

相关文章:

opencv - 检测台球 table 上的球

image - Matlab:找到轮廓并拉直近乎矩形的图像

python - 在 django 中设置 bool 请求 header 的格式

python - 在命令前添加 "sudo"使命令未知

c++ - 使用 openCV VC++ 读取文件 I/O

jquery - 使用 jQuery 清除 IMG

html - 删除 h1 标签的第一个字母

java - Android 上的着色图像处理

python - 敷面膜时颜色显示错误

Python - 如何使用其他 numpy 数组正确索引 numpy 数组,类似于 MATLAB