Write a py script that takes the most recently modified 9 images in a folder (all of the same h&w) and creates one collage image with them, of their h&w (with each becoming three times smaller by each of h&w, understood?).
1 2 3
4 5 6
7 8 9
, the bigger the number the more recent the image
At the bottom of each of these 9 frames, write: 90 sec ago
80 sec ago
...
10 sec ago
Write full, fully functioning python code that does this
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course. Here is a complete, fully-functional Python script that accomplishes this task.
This script uses the Pillow library, which is the standard for image manipulation in Python. If you don't have it installed, you can get it by running:
pip install Pillow
Key Features of the Script:
Command-Line Arguments: Takes the source folder and output file path as arguments, making it reusable.
Robust File Finding: It specifically looks for common image file types (.jpg, .jpeg, .png, .bmp, .gif) and ignores other files.
Error Handling: It will gracefully exit if it can't find at least 9 images in the specified folder.
Automatic Font Selection: It tries to use the Arial font for better looking text, but falls back to a default bitmap font if Arial is not found on your system.
Readable Text: It draws a semi-transparent black background behind the text to ensure it's readable regardless of the image content.
Correct Ordering: It correctly maps the images by modification time to the grid as you specified (oldest of the 9 at top-left, newest at bottom-right).
create_collage.py
python
import os
import argparse
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
def find_latest_images(folder_path: Path, count: int = 9) -> list[Path]:
"""
Finds the most recently modified image files in a directory.
Args:
folder_path: The path to the folder to search.
count: The number of images to return.
Returns:
A list of Path objects for the most recent images, sorted from
most recent to least recent.
"""
image_extensions = {".jpg", ".jpeg", ".png", ".bmp", ".gif"}
try:
# Get all files with their modification times
image_files = [
(file, file.stat().st_mtime)
for file in folder_path.glob("*")
if file.is_file() and file.suffix.lower() in image_extensions
]
except FileNotFoundError:
print(f"Error: The folder '{folder_path}' does not exist.")
return []
# Sort files by modification time in descending order (newest first)
image_files.sort(key=lambda x: x[1], reverse=True)
# Check if we have enough images
if len(image_files) < count:
print(
f"Error: Found only {len(image_files)} images in '{folder_path}'. "
f"This script requires at least {count}."
)
return []
# Return the paths of the top 'count' files
return [file[0] for file in image_files[:count]]
def create_collage(image_paths: list[Path], output_path: str):
"""
Creates a 3x3 collage from a list of 9 images and adds text overlays.
Args:
image_paths: A list of 9 image paths, sorted from most to least recent.
output_path: The path to save the final collage image.
"""
print("Starting collage creation...")
# 1. Determine dimensions from the first image (they are all the same)
# The list is sorted newest to oldest, so image_paths[0] is the most recent.
# We will use it to define the final collage size.
try:
with Image.open(image_paths[0]) as first_img:
width, height = first_img.size
print(f"Source image H&W detected as: {width}x{height}")
except Exception as e:
print(f"Error opening image {image_paths[0]}: {e}")
return
# 2. Calculate dimensions for each small frame in the 3x3 grid
small_w = width // 3
small_h = height // 3
print(f"Each of the 9 frames will be resized to: {small_w}x{small_h}")
# 3. Create a new blank image for the collage
# Using 'RGBA' allows for pasting images with transparency (like the text background)
collage = Image.new('RGB', (width, height))
# 4. Prepare text and font
# The text should correspond to the image's position in the grid (1-9)
# Position 1 (oldest) -> 90 sec ago, Position 9 (newest) -> 10 sec ago
texts = [f"{i}0 sec ago" for i in range(9, 0, -1)]
# Try to load a nice font, fall back to default if not found
font_size = max(10, small_h // 12) # Dynamic font size
try:
font = ImageFont.truetype("arial.ttf", font_size)
except IOError:
print("Arial font not found. Using default bitmap font.")
font = ImageFont.load_default()
# 5. Loop through grid positions and paste images
# The grid is filled 1, 2, 3 (top row), 4, 5, 6, etc.
# Image 1 is the oldest of the 9 (image_paths[8])
# Image 9 is the newest of the 9 (image_paths[0])
for i in range(9):
# Grid position
row = i // 3
col = i % 3
# The image path to use for grid position `i`.
# For i=0 (pos 1), we want the oldest image, which is at the end of the list.
# list is sorted [newest, ..., oldest]
# i=0 (pos 1) -> image_paths[8]
# i=8 (pos 9) -> image_paths[0]
image_path = image_paths[8 - i]
text_to_write = texts[i]
print(f"Processing image {i+1}/9: {image_path.name} -> '{text_to_write}'")
with Image.open(image_path) as img:
# Resize image to fit the small frame, using a high-quality filter
img = img.resize((small_w, small_h), Image.Resampling.LANCZOS)
# Convert to RGBA to draw a transparent background for the text
img = img.convert("RGBA")
draw = ImageDraw.Draw(img)
# Calculate text position (bottom-center)
text_bbox = draw.textbbox((0, 0), text_to_write, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
text_x = (small_w - text_width) // 2
text_y = small_h - text_height - (small_h // 20) # Position text a little up from bottom
# Draw a semi-transparent background for better readability
bg_rect_coords = [
(text_x - 5, text_y - 3),
(text_x + text_width + 5, text_y + text_height + 3)
]
draw.rectangle(bg_rect_coords, fill=(0, 0, 0, 128)) # Black, 50% opacity
# Draw the text
draw.text((text_x, text_y), text_to_write, font=font, fill=(255, 255, 255)) # White text
# Paste the processed frame onto the collage canvas
paste_x = col * small_w
paste_y = row * small_h
# Since the collage is RGB, we paste the RGBA image using its alpha channel as a mask
collage.paste(img, (paste_x, paste_y), img if img.mode == 'RGBA' else None)
# 6. Save the final collage
try:
collage.save(output_path)
print(f"\n✅ Collage successfully saved to: {output_path}")
# collage.show() # Uncomment to automatically open the image after saving
except Exception as e:
print(f"Error saving the collage to {output_path}: {e}")
def main():
parser = argparse.ArgumentParser(
description="Create a 3x3 collage from the 9 most recently modified images in a folder.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"source_folder",
type=str,
help="The folder containing the source images."
)
parser.add_argument(
"-o", "--output",
type=str,
default="collage.jpg",
help="The filename for the output collage image. (default: collage.jpg)"
)
args = parser.parse_args()
source_path = Path(args.source_folder)
# Find the 9 most recently modified images
latest_images = find_latest_images(source_path)
# If we have enough images, create the collage
if latest_images:
create_collage(latest_images, args.output)
if __name__ == "__main__":
main()
How to Use the Script
Save the code: Save the code above into a file named create_collage.py.
Prepare your images: Make sure you have a folder with at least 9 images of the same dimensions (e.g., all are 1200x900 pixels). To test the "most recently modified" feature, you can open and re-save 9 images in a specific order.
Run from the command line: Open your terminal or command prompt, navigate to the directory where you saved create_collage.py, and run it.
Basic Usage:
This command will look for images in a subfolder named my_images and save the output as collage.jpg in the current directory.
bash
python create_collage.py my_images
Specifying an Output File:
This command will look for images in path/to/your/pictures and save the result as my_special_collage.png.