Script Centered Text Python PIL

Date: 2021-07-11 | python | pil |

Overview

  • 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

Context

View this post on Instagram

A post shared by HAMY (@hamy.art)

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)

Code

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 = Image.new('RGBA', image.size, (255,255,255,0))

    font = ImageFont.truetype(
        font=font_path,
        size=font_size,
    )
    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))
    )

    image_draw.text(
        draw_point.to_tuple_int(),
        text,
        font=font,
        fill=color_rgb.to_bgr_tuple_alpha()
    )

    out_image = Image.alpha_composite(image, text_image)

    return out_image

Further Reading

Fin

Happy texting!

-HAMY.OUT

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.