Skip to content

Instantly share code, notes, and snippets.

@kennytrytek-wf
Last active January 6, 2026 19:07
Show Gist options
  • Select an option

  • Save kennytrytek-wf/9ae69d651cdf540d023c70fcf03f54f5 to your computer and use it in GitHub Desktop.

Select an option

Save kennytrytek-wf/9ae69d651cdf540d023c70fcf03f54f5 to your computer and use it in GitHub Desktop.
Scale one or more images to fit within a certain size, and add an outline of the desired thickness.
#!/usr/bin/env python3
"""
Image Processing Script
Processes images by scaling them proportionally and adding borders.
"""
import os
import sys
from pathlib import Path
from PIL import Image
def process_image(input_path, output_dir, max_size_inches=2, border_inches=0.02, dpi=300):
"""
Process a single image: scale proportionally and add border.
Args:
input_path: Path to input image
output_dir: Directory to save processed image
max_size_inches: Maximum dimension (width or height) in inches
border_inches: Border width in inches
dpi: Dots per inch for size calculations
"""
try:
# Open the image
img = Image.open(input_path)
# Convert inches to pixels
max_size_px = int(max_size_inches * dpi)
border_px = int(border_inches * dpi)
# Get current dimensions
width, height = img.size
# Calculate scaling factor (proportional)
scale_factor = min(max_size_px / width, max_size_px / height)
# Only scale down, not up
if scale_factor < 1:
new_width = int(width * scale_factor)
new_height = int(height * scale_factor)
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Create new image with border
final_width = img.width + (2 * border_px)
final_height = img.height + (2 * border_px)
# Create black background
bordered_img = Image.new('RGB', (final_width, final_height), 'black')
# Paste original image centered on black background
bordered_img.paste(img, (border_px, border_px))
# Save to output directory with same filename
output_path = Path(output_dir) / Path(input_path).name
bordered_img.save(output_path, quality=95)
print(f"✓ Processed: {Path(input_path).name}")
return True
except Exception as e:
print(f"✗ Error processing {Path(input_path).name}: {e}")
return False
def main():
"""Main function to process all images in input directory."""
if len(sys.argv) != 3:
print("Usage: python image_processor.py <input_directory> <output_directory>")
sys.exit(1)
input_dir = Path(sys.argv[1])
output_dir = Path(sys.argv[2])
# Validate input directory
if not input_dir.exists():
print(f"Error: Input directory '{input_dir}' does not exist.")
sys.exit(1)
if not input_dir.is_dir():
print(f"Error: '{input_dir}' is not a directory.")
sys.exit(1)
# Create output directory if it doesn't exist
output_dir.mkdir(parents=True, exist_ok=True)
# Supported image formats
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.webp'}
# Find all images in input directory
image_files = [
f for f in input_dir.iterdir()
if f.is_file() and f.suffix.lower() in image_extensions
]
if not image_files:
print(f"No images found in '{input_dir}'")
sys.exit(0)
print(f"Found {len(image_files)} image(s) to process...")
print()
# Process each image
successful = 0
for image_path in image_files:
if process_image(image_path, output_dir):
successful += 1
print()
print(f"Complete: {successful}/{len(image_files)} images processed successfully.")
if __name__ == "__main__":
main()

This Python script processes images by proportionally scaling them down to fit within a specified maximum dimension (default 2 inches) and adding a black border around them. It uses the Pillow library to handle image manipulation and preserves the aspect ratio of each image while converting dimensions from inches to pixels based on a configurable DPI setting (default 300).

To use the script, run it from the command line with two arguments: python image_outline_scaler.py <input_directory> <output_directory>. The script scans the input directory for supported image formats (JPG, PNG, BMP, GIF, TIFF, WebP), processes each image by scaling and adding borders, and saves the results to the output directory with the same filenames. It provides feedback on successful and failed conversions.

This tool is ideal for preparing images for inclusion in multi-image documents where file size optimization is critical, such as creating reports, presentations, or documentation compilations. The uniform scaling and border styling ensure consistent visual presentation across many images, while the reduced dimensions and JPEG quality compression (95%) significantly minimize file sizes, making documents easier to share and store.

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