Search code examples
pythonimagepython-imaging-libraryimage-manipulation

How do I Anchor Text and Shrink it to fit it on an Image


I fount this code off of the PIL API(here is the link: https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html) and I wanted to also shrink it depending on the size of the text while it is centered.

here is the anchoring code

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')

And the outcome looks like this:

enter image description here

But if you increase the word size it looks like this:

enter image description here

So I just want the text to be centered and shrunk to fit the image


Solution

  • No detail about the requirements, so here only for result image with fixed size (200, 200), so font size will be changed.

    • Find the size of text by ImageDraw.textsize
    • Draw on an image with same width as the text by ImageDraw.text
    • Resize image to (200-2*border, 200-2*border) by Image.resize
    • Paste the resized image to a 200x200 image by Image.paste
    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")
    

    enter image description here