Add Text to Image with Pillow

  • Share this:

Code introduction


This function uses the Pillow library to add text to an image. It takes the image path, text to add, text position, font path, and font size as parameters.


Technology Stack : Pillow, Image, ImageFilter, ImageDraw, ImageFont

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageFilter, ImageDraw, ImageFont

def add_text_to_image(image_path, text, position, font_path='arial.ttf', font_size=20):
    """
    This function adds text to an image using the Pillow library.
    """
    # Load the image
    img = Image.open(image_path)
    
    # Create a drawing context
    draw = ImageDraw.Draw(img)
    
    # Load the font
    font = ImageFont.truetype(font_path, font_size)
    
    # Add text to the image
    draw.text(position, text, font=font, fill=(255, 255, 255))
    
    # Save the image
    img.save('output_image_with_text.png')