Advertisement
Guest User

Untitled

a guest
Nov 13th, 2023
20
0
158 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | Source Code | 0 0
  1. #!/usr/bin/env python3
  2. import os
  3. from pathlib import Path
  4. from PIL import Image, ImageDraw, ImageFont
  5.  
  6. def resize_image(image, width):
  7.     aspect_ratio = float(image.height) / float(image.width)
  8.     height = int(width * aspect_ratio)
  9.     return image.resize((width, height), Image.ANTIALIAS)
  10.  
  11. def add_text_to_image(image, text):
  12.     draw = ImageDraw.Draw(image)
  13.     # Calculate the font size based on the image width and text length
  14. #    font_size = int(image.width // len(text))
  15.     font_size = 1
  16.     font = ImageFont.truetype("impact.ttf", font_size)
  17.  
  18.     # Adjust the font size to fit the text horizontally
  19.     while font.getsize(text)[0] < image.width * 0.95 and font_size < 75:
  20.         font_size += 1
  21.         font = ImageFont.truetype("impact.ttf", font_size)
  22.    
  23.     text_width, text_height = font.getsize(text)
  24.  
  25.     x = (image.width - text_width) // 2
  26.     y = image.height - text_height - int(image.height * 0.05)
  27.     outline_thickness = 2
  28.  
  29.     for dx in range(-outline_thickness, outline_thickness + 1):
  30.         for dy in range(-outline_thickness, outline_thickness + 1):
  31.             draw.text((x + dx, y + dy), text, font=font, fill="black")
  32.    
  33.     draw.text((x, y), text, font=font, fill="white")
  34.    
  35.     return image
  36.  
  37. def process_images_in_directory(directory):
  38.     directory_path = Path(directory) / 'images'
  39.    
  40.     for image_file in directory_path.glob("*.png"):
  41.         image = Image.open(image_file)
  42.  
  43.         resized_image = resize_image(image, 250)
  44.         text = image_file.stem
  45.         processed_image = add_text_to_image(resized_image, text)
  46.  
  47.         output_path = Path(directory) / 'processed' / image_file.name
  48.         processed_image.save(output_path)
  49.  
  50. if __name__ == "__main__":
  51.     directory = "."
  52.     process_images_in_directory(directory)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement