Skip to content

Instantly share code, notes, and snippets.

@ccerv1
Created January 14, 2025 21:08
Show Gist options
  • Select an option

  • Save ccerv1/134ab4adcf2042794b92d72f5cafe8dd to your computer and use it in GitHub Desktop.

Select an option

Save ccerv1/134ab4adcf2042794b92d72f5cafe8dd to your computer and use it in GitHub Desktop.
text-on-image.py
from PIL import Image, ImageDraw, ImageFont
import os
def add_text_to_images(directory, output_directory, text):
# Create the output directory if it doesn't exist
os.makedirs(output_directory, exist_ok=True)
# Loop through all PNG files in the directory
for filename in os.listdir(directory):
print(filename)
if filename.lower().endswith(".png"):
file_path = os.path.join(directory, filename)
# Open the image
with Image.open(file_path) as img:
# Create a drawing context
draw = ImageDraw.Draw(img)
# Define text position
text_x = int(img.width * 0.10)
text_y = int(img.height * 0.05)
# Load the font from your system
font = ImageFont.truetype("/System/Library/Fonts/Supplemental/Arial.ttf", 48)
# Draw the text on the image in black with larger font
draw.text((text_x, text_y), text, fill="black", font=font)
# Save the modified image
output_path = os.path.join(output_directory, filename)
img.save(output_path)
print(f"Processed and saved: {output_path}")
# Main
input_directory = input("Enter the directory containing PNG files: ")
output_directory = input("Enter the directory to save processed images: ")
text_to_add = input("Enter the text to add to images: ")
add_text_to_images(input_directory, output_directory, text_to_add)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment