Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import os
- from pathlib import Path
- from PIL import Image, ImageDraw, ImageFont
- def resize_image(image, width):
- aspect_ratio = float(image.height) / float(image.width)
- height = int(width * aspect_ratio)
- return image.resize((width, height), Image.ANTIALIAS)
- def add_text_to_image(image, text):
- draw = ImageDraw.Draw(image)
- # Calculate the font size based on the image width and text length
- # font_size = int(image.width // len(text))
- font_size = 1
- font = ImageFont.truetype("impact.ttf", font_size)
- # Adjust the font size to fit the text horizontally
- while font.getsize(text)[0] < image.width * 0.95 and font_size < 75:
- font_size += 1
- font = ImageFont.truetype("impact.ttf", font_size)
- text_width, text_height = font.getsize(text)
- x = (image.width - text_width) // 2
- y = image.height - text_height - int(image.height * 0.05)
- outline_thickness = 2
- for dx in range(-outline_thickness, outline_thickness + 1):
- for dy in range(-outline_thickness, outline_thickness + 1):
- draw.text((x + dx, y + dy), text, font=font, fill="black")
- draw.text((x, y), text, font=font, fill="white")
- return image
- def process_images_in_directory(directory):
- directory_path = Path(directory) / 'images'
- for image_file in directory_path.glob("*.png"):
- image = Image.open(image_file)
- resized_image = resize_image(image, 250)
- text = image_file.stem
- processed_image = add_text_to_image(resized_image, text)
- output_path = Path(directory) / 'processed' / image_file.name
- processed_image.save(output_path)
- if __name__ == "__main__":
- directory = "."
- process_images_in_directory(directory)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement