Script Centered Text Python PIL

2021.07.11 | 275 words |


  • Released Labeled Intentions last week which is centered around centered text
  • Built with Python PIL and needed to write own centered text function - figured others might need this too


Labeled Intentions

Labeled Intentions is my newest art project which explores the meaning of labels through shirts with labels attached. This involves:

  • Creating images with centered text (labels)
  • Putting them on shirts

I chose to create these images using a Python script leveraging the Python PIL library (You can read more about this decision in: Scripting Labeled Intentions with Python PIL)


The code works like this:

  • Create a new transparent image of the same size of the OG image that we want to put our text on -> call this text_image
  • Load the font
  • Create a PIL ImageDraw
  • Find the width and height of the output text
  • Calculate the top left corner of the text box in order to center on the given point
  • Draw the text onto text_image
  • Now overlay text_image onto the original image
from Domain.Models.Point import Point
from Domain.Models.RGBA import RGBA
from PIL import Image, ImageDraw, ImageFont

def draw_centered_text_on_image(
    image: Image,
    center_point: Point,
    text: str,
    font_path: str,
    font_size: int,
    color_rgb: RGBA
) -> Image:
    Draws centered text on image
    text_image ='RGBA', image.size, (255,255,255,0))

    font = ImageFont.truetype(
    image_draw = ImageDraw.Draw(text_image)

    text_width, text_height = image_draw.textsize(text, font)

    draw_point = Point(
        (center_point.x - (text_width / 2)),
        (center_point.y - (text_height / 2))


    out_image = Image.alpha_composite(image, text_image)

    return out_image

Further Reading


Happy texting!



About the Ham

Hi I'm Hamilton - I built this! If you want more content like this subscribe to my email list, connect with me around the web, or take a look at some of my other projects.

More Projects

comments powered by Disqus