Create thumbnails maintaining aspect ratio. If the target box is 100x100 but the image…
- User
Create thumbnails maintaining aspect ratio. If the target box is 100x100 but the image is 200x100, resize to 100x50 and paste it centered on a 100x100 white background canvas for uniform output dimensions.
Assistant
The user wants me to create a solution for generating thumbnails while maintaining aspect ratio. This is a common requirement in image processing where you want:
- Uniform output dimensions (e.g., 100x100)
- Maintain the original image's aspect ratio
- Center the resized image on a colored background (padding)
This is commonly called "letterboxing" or "pillarboxing" depending on the dimensions.
Let me provide a comprehensive solution using Python with PIL/Pillow, which is the most common approach. I'll also consider other popular libraries and approaches.
Key steps:
- Open the image
- Calculate the scaling factor to fit within target dimensions while maintaining aspect ratio
- Resize the image
- Create a background canvas with the target dimensions
- Calculate position to center the image
- Paste the resized image onto the canvas
Let me provide multiple implementations and examples.
Thumbnail Generation with Aspect Ratio Preservation
Here are practical implementations for creating thumbnails with centered padding:
1. Using PIL/Pillow (Python)
from PIL import Image from pathlib import Path def create_thumbnail(image_path, output_size=(100, 100), bg_color='white'): """ Create a thumbnail maintaining aspect ratio with padding. Args: image_path: Path to input image output_size: Target dimensions (width, height) bg_color: Background color for padding Returns: PIL Image object """ # Open and convert image img = Image.open(image_path).convert('RGB') # Calculate scaling to fit in output_size while maintaining aspect ratio img.thumbnail(output_size, Image.Resampling.LANCZOS) # Create white background canvas canvas = Image.new('RGB', output_size, bg_color) # Calculate position to center image x = (output_size[0] - img.width) // 2 y = (output_size[1] - img.height) // 2 # Paste resized image onto canvas canvas.paste(img, (x, y)) return canvas # Example usage thumb = create_thumbnail('photo.jpg', output_size=(100, 100)) thumb.save('thumbnail.jpg', quality=85)2. Batch Processing Multiple Images
from PIL import Image from pathlib import Path def batch_create_thumbnails(input_dir, output_dir, size=(100, 100), bg_color='white'): """Process all images in a directory.""" Path(output_dir).mkdir(exist_ok=True) for image_path in Path(input_dir).glob('*.jpg'): try: img = Image.open(image_path).convert('RGB') img.thumbnail(size, Image.Resampling.LANCZOS) canvas = Image.new('RGB', size, bg_color) x = (size[0] - img.width) // 2 y = (size[1] - img.height) // 2 canvas.paste(img, (x, y)) output_path = Path(output_dir) / f"thumb_{image_path.name}" canvas.save(output_path, quality=85, optimize=True) print(f"✓ {image_path.name}") except Exception as e: print(f"✗ {image_path.name}: {e}") # Usage batch_create_thumbnails('./images', './thumbnails', size=(150, 150))3. Advanced Version with Options
from PIL import Image from enum import Enum class ResizeMode(Enum): FIT = 1 # Maintain AR, center with padding FILL = 2 # Crop to fill (may cut image) COVER = 3 # Scale to cover, then crop center def create_thumbnail_advanced( image_path, output_size=(100, 100), mode=ResizeMode.FIT, bg_color='white', quality=85 ): """ Advanced thumbnail generator with multiple resize modes. """ img = Image.open(image_path).convert('RGB') target_w, target_h = output_size orig_w, orig_h = img.size if mode == ResizeMode.FIT: # Fit within bounds, maintain AR, add padding img.thumbnail(output_size, Image.Resampling.LANCZOS) canvas = Image.new('RGB', output_size, bg_color) x = (target_w - img.width) // 2 y = (target_h - img.height) // 2 canvas.paste(img, (x, y)) elif mode == ResizeMode.COVER: # Scale to cover entire canvas, crop center scale = max(target_w / orig_w, target_h / orig_h) new_size = (int(orig_w * scale), int(orig_h * scale)) img = img.resize(new_size, Image.Resampling.LANCZOS) # Crop center left = (img.width - target_w) // 2 top = (img.height - target_h) // 2 canvas = img.crop((left, top, left + target_w, top + target_h)) elif mode == ResizeMode.FILL: # Distort to fill (not recommended for photos) canvas = img.resize(output_size, Image.Resampling.LANCZOS) return canvas # Usage examples thumb_fit = create_thumbnail_advanced('photo.jpg', mode=ResizeMode.FIT) thumb_cover = create_thumbnail_advanced('photo.jpg', mode=ResizeMode.COVER)4. Using OpenCV (High Performance)
import cv2 import numpy as np def create_thumbnail_opencv(image_path, output_size=(100, 100), bg_color=(255, 255, 255)): """OpenCV implementation for better performance with large batches.""" img = cv2.imread(image_path) h, w = img.shape[:2] target_w, target_h = output_size # Calculate scale to fit scale = min(target_w / w, target_h / h) new_w, new_h = int(w * scale), int(h * scale) # Resize img_resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LANCZOS4) # Create canvas canvas = np.full((target_h, target_w, 3), bg_color, dtype=np.uint8) # Calculate position x = (target_w - new_w) // 2 y = (target_h - new_h) // 2 # Paste image canvas[y:y+new_h, x:x+new_w] = img_resized return canvas # Usage thumb = create_thumbnail_opencv('photo.jpg') cv2.imwrite('thumbnail.jpg', thumb)5. Web Image Handling (with URL)
from PIL import Image from io import BytesIO import requests def create_thumbnail_from_url(image_url, output_size=(100, 100)): """ Create thumbnail from remote image URL. """ response = requests.get(image_url, timeout=10) img = Image.open(BytesIO(response.content)).convert('RGB') img.thumbnail(output_size, Image.Resampling.LANCZOS) canvas = Image.new('RGB', output_size, 'white') x = (output_size[0] - img.width) // 2 y = (output_size[1] - img.height) // 2 canvas.paste(img, (x, y)) return canvas # Usage thumb = create_thumbnail_from_url('https://example.com/image.jpg')6. CLI Tool
#!/usr/bin/env python3 import click from PIL import Image from pathlib import Path @click.command() @click.argument('input_dir', type=click.Path(exists=True)) @click.option('--output', '-o', default='./thumbnails', help='Output directory') @click.option('--size', '-s', nargs=2, type=int, default=[100, 100], help='Output size') @click.option('--bg', default='white', help='Background color') @click.option('--quality', '-q', type=int, default=85, help='JPEG quality') def generate_thumbnails(input_dir, output, size, bg, quality): """Generate thumbnails maintaining aspect ratio.""" Path(output).mkdir(parents=True, exist_ok=True) total, success = 0, 0 for img_path in Path(input_dir).glob('**/*.{jpg,jpeg,png,webp}'): total += 1 try: img = Image.open(img_path).convert('RGB') img.thumbnail(size, Image.Resampling.LANCZOS) canvas = Image.new('RGB', tuple(size), bg) x = (size[0] - img.width) // 2 y = (size[1] - img.height) // 2 canvas.paste(img, (x, y)) out_path = Path(output) / f"thumb_{img_path.name}" canvas.save(out_path, quality=quality, optimize=True) success += 1 click.echo(f"✓ {img_path.name}") except Exception as e: click.echo(f"✗ {img_path.name}: {e}", err=True) click.echo(f"\nProcessed: {success}/{total}") if __name__ == '__main__': generate_thumbnails()7. Output Comparison
Original: 200x100 Target: 100x100 Result: 100x50 (resized) + 25px white padding top/bottom Original: 100x200 Target: 100x100 Result: 50x100 (resized) + 25px white padding left/right Original: 150x150 Target: 100x100 Result: 100x100 (exact fit, no padding)Key Considerations
Factor Recommendation Quality Use LANCZOSresampler for best qualityPerformance Use thumbnail()for efficiencyFormat JPEG for photos, PNG for graphics Background White, transparent, or dominant color Memory Process in batches for large datasets Choose the implementation based on your needs: PIL for simplicity, OpenCV for performance, or requests for remote images.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.