Image Text Overlay Function

  • Share this:

Code introduction


This function draws text on an image. It first loads the image, then creates a drawing context, loads the font, and finally draws the text at a specified position and saves the image.


Technology Stack : Pillow

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageDraw, ImageFont

def draw_text_on_image(image_path, text, position, font_path):
    # Load the image
    image = Image.open(image_path)
    
    # Create a drawing context
    draw = ImageDraw.Draw(image)
    
    # Load the font
    try:
        font = ImageFont.truetype(font_path, size=50)
    except IOError:
        font = ImageFont.load_default()
    
    # Draw the text onto the image
    draw.text(position, text, font=font, fill=(255, 255, 255))
    
    # Save the image
    image.save('output_image.png')                
              
Tags: