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 resultsTask:
Optimize this code so it can efficiently process 1000+ images. Make it production-ready with good error handling, progress indication, and performance.