Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created May 12, 2026 15:50
Show Gist options
  • Select an option

  • Save decagondev/2656de88fe43db01430a59c83da4b067 to your computer and use it in GitHub Desktop.

Select an option

Save decagondev/2656de88fe43db01430a59c83da4b067 to your computer and use it in GitHub Desktop.

You are given the following slow Python function that processes images (resizes them and adds a watermark). It becomes painfully slow when processing hundreds or thousands of images.

from PIL import Image, ImageDraw, ImageFont
import os
from typing import List, Tuple

def process_images(input_dir: str, output_dir: str, watermark_text: str = "CONFIDENTIAL") -> List[Tuple[str, bool]]:
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    results = []
    for filename in os.listdir(input_dir):
        if not filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            continue
            
        input_path = os.path.join(input_dir, filename)
        output_path = os.path.join(output_dir, filename)
        
        try:
            # Open image
            img = Image.open(input_path)
            
            # Resize
            max_width = 1200
            if img.width > max_width:
                ratio = max_width / img.width
                new_height = int(img.height * ratio)
                img = img.resize((max_width, new_height), Image.LANCZOS)
            
            # Add watermark
            draw = ImageDraw.Draw(img)
            try:
                font = ImageFont.truetype("arial.ttf", 36)
            except:
                font = ImageFont.load_default()
            
            # Simple text placement (bottom right)
            text_width = draw.textlength(watermark_text, font=font)
            position = (img.width - text_width - 20, img.height - 50)
            draw.text(position, watermark_text, fill=(255, 255, 255, 128), font=font)
            
            img.save(output_path, quality=85)
            results.append((filename, True))
            
        except Exception as e:
            results.append((filename, False))
            print(f"Error processing {filename}: {e}")
    
    return results

Task:
Optimize this code so it can efficiently process 1000+ images. Make it production-ready with good error handling, progress indication, and performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment