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

Time:12-21

I fount this code off of the PIL API(here is the link: 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

CodePudding user response:

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

  • Related