【问题标题】:How do I Anchor Text and Shrink it to fit it on an Image如何锚定文本并将其缩小以适合图像
【发布时间】:2022-01-21 16:31:23
【问题描述】:

我从 PIL API 中找到了这段代码(这里是链接:https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html),我还想根据居中时的文本大小来缩小它。

这里是锚定代码

from PIL import Image, ImageDraw, ImageFont

font = ImageFont.truetype("mont.ttf", 48)
im = Image.new("RGB", (200, 200), "white")
d = ImageDraw.Draw(im)
d.text((100, 100), "Quick", fill="black", anchor="ms", font=font)
im.save('text.png')

结果是这样的:

但如果你增加字长,它看起来像这样:

所以我只希望文本居中并缩小以适合图像

【问题讨论】:

标签: python image python-imaging-library image-manipulation


【解决方案1】:

没有具体要求,所以这里只针对固定大小(200、200)的结果图,所以字体大小会改变。

  • 通过ImageDraw.textsize查找文本大小
  • 在与ImageDraw.text的文本宽度相同的图像上绘制
  • 通过Image.resize将图像大小调整为(200-2*border, 200-2*border)
  • 将调整大小的图像粘贴到Image.paste的200x200图像
from PIL import Image, ImageDraw, ImageFont

def text_to_image(text, filename='text.png', border=20):
    im = Image.new("RGB", (1, 1), "white")
    font = ImageFont.truetype("calibri.ttf", 48)
    draw = ImageDraw.Draw(im)
    size = draw.textsize(text, font=font)
    width = max(size)
    im = Image.new("RGB", (width, width), "white")
    draw = ImageDraw.Draw(im)
    draw.text((width//2, width//2), text, anchor='mm', fill="black", font=font)
    im = im.resize((200-2*border, 200-2*border), resample=Image.LANCZOS)
    new_im = Image.new("RGB", (200, 200), "white")
    new_im.paste(im, (border, border))
    new_im.show()
    # new_im.save(filename)

text_to_image("Hello World")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 2017-11-25
    • 2013-02-10
    • 1970-01-01
    • 2019-11-09
    • 2011-09-03
    • 2015-09-01
    • 2015-04-20
    相关资源
    最近更新 更多