Skip to content

ng-technology-llc/image-converter

Repository files navigation

Image to WebP Converter

A comprehensive Python script that automatically converts all images in a folder to WebP format with intelligent format detection, batch processing capabilities, and advanced compression options.

📋 Table of Contents

🔍 Overview

This tool provides an efficient solution for batch converting images to the modern WebP format, which offers superior compression while maintaining high image quality. WebP typically reduces file sizes by 25-50% compared to JPEG and PNG while preserving visual quality.

Why WebP?

  • Better Compression: Up to 50% smaller file sizes than JPEG/PNG
  • Universal Support: Supported by all modern browsers
  • Transparency Support: Like PNG, but with better compression
  • Animation Support: Can replace animated GIFs
  • Lossless & Lossy: Choose the best compression method for your needs

✨ Features

Core Functionality

  • 🔍 Auto-detection: Automatically identifies and processes multiple image formats
  • 📦 Batch processing: Converts entire folders of images in one operation
  • 🎛️ Quality control: Adjustable quality settings (1-100) for optimal size/quality balance
  • 🔄 Lossless option: Support for lossless WebP compression
  • 🎨 Smart transparency handling: Properly handles RGBA and LA images
  • 📊 Progress tracking: Real-time conversion progress with detailed statistics
  • 🛡️ Safe operation: Won't overwrite existing files unless explicitly requested
  • ⚡ Fast processing: Optimized for speed with efficient image processing
  • 📝 Detailed logging: Comprehensive output showing file sizes and compression ratios

Advanced Features

  • 🔧 Flexible output: Custom output directories or automatic subfolder creation
  • 🎯 Selective processing: Skip existing files or force overwrite
  • 📈 Compression statistics: Detailed before/after file size comparisons
  • ❌ Error resilience: Individual file errors won't stop batch processing
  • 🔍 Format validation: Automatic detection of corrupted or invalid image files

💻 System Requirements

Minimum Requirements

  • Python: 3.6 or higher
  • RAM: 512MB (for basic usage)
  • Storage: Sufficient space for output files (typically 25-75% of original size)
  • OS: Windows, macOS, or Linux

Recommended Requirements

  • Python: 3.8 or higher
  • RAM: 2GB+ for processing large images or many files
  • CPU: Multi-core processor for faster processing
  • Storage: SSD for improved I/O performance

Tested Platforms

  • ✅ macOS 10.15+ (Intel & Apple Silicon)
  • ✅ Windows 10/11
  • ✅ Ubuntu 18.04+
  • ✅ CentOS 7+
  • ✅ Debian 10+

🚀 Installation

Method 1: Quick Install (Recommended)

# Clone or download the script
# Install dependencies
pip3 install -r requirements.txt

Method 2: Manual Installation

# Install Pillow directly
pip3 install Pillow>=10.0.0

# Or using conda
conda install Pillow

# Or using brew (macOS)
brew install pillow

Method 3: Virtual Environment (Best Practice)

# Create virtual environment
python3 -m venv webp_converter_env

# Activate virtual environment
# On macOS/Linux:
source webp_converter_env/bin/activate
# On Windows:
webp_converter_env\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Verification

# Test the installation
python3 image_converter.py --help

# Check Pillow installation
python3 -c "from PIL import Image; print('Pillow installed successfully')"

🖼️ Supported Image Formats

Input Formats (Auto-detected)

Format Extensions Notes
JPEG .jpg, .jpeg Most common photo format
PNG .png Supports transparency
BMP .bmp Windows bitmap format
TIFF .tiff, .tif High-quality format, multiple pages supported
GIF .gif Animated GIFs converted to static WebP
ICO .ico Windows icon format
PPM .ppm Portable Pixmap format
PGM .pgm Portable Graymap format
PBM .pbm Portable Bitmap format
WebP .webp For quality/compression changes

Output Format

  • WebP: Modern format with excellent compression and quality

Format-Specific Handling

  • JPEG: Direct conversion with quality mapping
  • PNG with transparency: Preserves transparency in lossless mode, converts to white background in lossy mode
  • Animated GIF: Converts to static WebP (first frame)
  • TIFF multi-page: Converts first page only
  • High bit-depth images: Automatically converted to 8-bit

📚 Usage

Basic Syntax

python3 image_converter.py <input_folder> [options]

Quick Start Examples

# Convert all images in current directory
python3 image_converter.py .

# Convert images in specific folder
python3 image_converter.py /path/to/your/images

# Convert with high quality
python3 image_converter.py /path/to/images -q 95

# Convert with custom output folder
python3 image_converter.py /path/to/images -o ./webp_output

⚙️ Command Line Options

Required Arguments

Argument Description Example
folder Path to folder containing images /home/user/photos

Optional Arguments

Option Long Form Type Default Description
-h --help - - Show help message and exit
-o --output string webp_converted/ Output folder path
-q --quality int 85 WebP quality (1-100)
--lossless flag false Use lossless compression
--overwrite flag false Overwrite existing files

Quality Guidelines

Quality Use Case File Size Visual Quality
1-30 Thumbnails, previews Smallest Low
31-50 Web thumbnails Small Acceptable
51-70 Standard web images Medium Good
71-85 Default - balanced Medium-Large High
86-95 Photography, important images Large Very High
96-100 Professional/archival Largest Maximum
Lossless Graphics, logos, text Variable Perfect

📖 Examples

Basic Operations

# Convert images in Downloads folder
python3 image_converter.py ~/Downloads

# Convert vacation photos with high quality
python3 image_converter.py ~/Pictures/vacation -q 95

# Convert screenshots with lossless compression
python3 image_converter.py ~/Pictures/screenshots --lossless

Advanced Operations

# Convert to specific output with overwrite
python3 image_converter.py ./raw_images -o ./optimized_images --overwrite

# High-quality conversion for print materials
python3 image_converter.py ./print_photos -q 98 -o ./web_ready

# Lossless conversion for graphics/logos
python3 image_converter.py ./logos --lossless -o ./webp_logos

# Batch process multiple quality levels
python3 image_converter.py ./originals -q 60 -o ./web_small
python3 image_converter.py ./originals -q 85 -o ./web_medium
python3 image_converter.py ./originals -q 95 -o ./web_large

Real-World Scenarios

# E-commerce product photos
python3 image_converter.py ./product_photos -q 80 -o ./website_images

# Blog post images
python3 image_converter.py ./blog_images -q 75 -o ./compressed

# Social media optimization
python3 image_converter.py ./social_content -q 70 -o ./social_webp

# Archive high-quality photos
python3 image_converter.py ./family_photos --lossless -o ./archive_webp

🔧 Technical Details

Image Processing Pipeline

  1. Discovery: Recursively scan input folder for image files
  2. Validation: Verify file format and integrity
  3. Analysis: Determine optimal conversion strategy
  4. Processing: Apply format-specific conversions
  5. Optimization: Apply WebP compression settings
  6. Output: Save to designated folder with progress tracking

Memory Management

  • Streaming: Large images processed in chunks to minimize RAM usage
  • Garbage Collection: Automatic cleanup of temporary image objects
  • Buffer Limits: Automatic adjustment for available system memory

Compression Algorithms

  • Lossy: VP8 encoding with configurable quality
  • Lossless: Advanced predictive encoding
  • Method 6: Best compression ratio (slower but smaller files)

Transparency Handling

# RGBA images in lossy mode
if img.mode == 'RGBA' and not lossless:
    # Create white background composite
    background = Image.new('RGB', img.size, (255, 255, 255))
    background.paste(img, mask=img.split()[-1])

📊 Output Information

Console Output Example

Found 25 image files to convert...
Output folder: /Users/nick/photos/webp_converted
Quality: 85%
--------------------------------------------------
Converting IMG_001.jpg... ✓ (Size: 3,247,891 → 1,456,234 bytes, 55.2% reduction)
Converting screenshot.png... ✓ (Size: 892,456 → 445,123 bytes, 50.1% reduction)
Converting logo.png... ✓ (Size: 156,789 → 89,234 bytes, 43.1% reduction)
Skipping existing.webp (already WebP)
Converting photo.tiff... ✓ (Size: 8,934,567 → 2,123,890 bytes, 76.2% reduction)
--------------------------------------------------
Conversion complete!
Successfully converted: 24 files
Skipped: 1 files
Total size reduction: 67.3% (45.2 MB → 14.8 MB)

File Organization

input_folder/
├── image1.jpg
├── image2.png
└── webp_converted/          # Default output folder
    ├── image1.webp
    └── image2.webp

Statistics Tracked

  • Files processed: Total count of converted files
  • Files skipped: Count and reasons for skipped files
  • Size reduction: Individual and aggregate compression ratios
  • Processing time: Time taken for each file and total operation
  • Error count: Number of failed conversions with details

❌ Error Handling

Common Errors and Solutions

ModuleNotFoundError: No module named 'PIL'

# Solution: Install Pillow
pip3 install Pillow

Permission denied errors

# Solution: Check folder permissions
chmod 755 /path/to/input/folder
chmod 755 /path/to/output/folder

FileNotFoundError: Folder does not exist

# Solution: Verify path exists
ls -la /path/to/folder

Memory errors with large images

# Solution: Process files individually or increase system memory
python3 image_converter.py /path/to/large/images -q 70  # Lower quality uses less memory

Error Recovery

  • Individual file failures: Don't stop batch processing
  • Detailed error messages: Specific information about what went wrong
  • Graceful degradation: Continue with remaining files
  • Exit codes: Proper return codes for scripting

⚡ Performance Considerations

Optimization Tips

  1. Quality Settings: Lower quality = faster processing
  2. Output Location: Use SSD for faster I/O
  3. File Size: Smaller images process faster
  4. Batch Size: Process 100-500 files at a time for optimal performance
  5. System Resources: Close other applications during large batch operations

Performance Benchmarks

Image Count Average Size Quality Processing Time
10 files 2MB 85 ~15 seconds
100 files 2MB 85 ~2 minutes
1000 files 2MB 85 ~15 minutes
100 files 10MB 95 ~8 minutes

Memory Usage

  • Base usage: ~50MB
  • Per image: ~3x original image size during processing
  • Large images (>20MB): May require 500MB+ RAM temporarily

🔧 Troubleshooting

Installation Issues

# Python version check
python3 --version  # Should be 3.6+

# Pillow installation verification
python3 -c "from PIL import Image; print('OK')"

# Alternative installation methods
pip install --user Pillow  # User-specific install
sudo pip3 install Pillow   # System-wide (Linux/macOS)

Runtime Issues

# Check file permissions
ls -la input_folder/
ls -la output_folder/

# Verify image files
file input_folder/*  # Shows file types

# Test with single file
python3 image_converter.py single_image_folder/

Common Solutions

Problem Solution
Script won't run Check Python 3.6+ installed
No images found Verify supported formats in folder
Output folder missing Script creates it automatically
Conversion fails Check individual file integrity
Slow performance Reduce quality or image size

❓ FAQ

General Questions

Q: What's the difference between lossy and lossless WebP? A: Lossy WebP uses advanced compression that may slightly reduce quality but creates much smaller files. Lossless WebP preserves perfect quality but with larger file sizes than lossy mode.

Q: Can I convert animated GIFs? A: The script converts the first frame of animated GIFs to static WebP. For animated WebP, you'd need specialized tools.

Q: Will this work with RAW camera files? A: No, RAW formats (.CR2, .NEF, .ARW, etc.) are not supported. Convert to JPEG/TIFF first.

Q: How much space will I save? A: Typically 25-50% reduction in file size. JPEG photos often see 30-40% reduction, PNG images can see 50-80% reduction.

Technical Questions

Q: What happens to image metadata (EXIF)? A: Basic metadata is preserved, but some camera-specific EXIF data may be lost during conversion.

Q: Can I process images recursively in subdirectories? A: Currently no, the script only processes the specified folder. Run it separately on each subdirectory.

Q: Is there a file size limit? A: No hard limit, but very large files (>100MB) may require significant RAM and processing time.

Usage Questions

Q: Can I undo the conversion? A: No, this is a one-way conversion. The script doesn't modify original files, so you always have the originals.

Q: What quality setting should I use? A: For most uses, the default (85) is excellent. Use 95+ for important photos, 70-80 for web images, or lossless for graphics/logos.

Q: Can I batch convert with different settings? A: Run the script multiple times with different quality settings and output folders.

🤝 Contributing

Reporting Issues

  1. Check existing issues on GitHub
  2. Provide detailed error messages
  3. Include Python version and OS information
  4. Attach sample problematic images (if possible)

Feature Requests

  • Recursive subdirectory processing
  • GUI interface
  • Animated WebP support
  • Progress bars for large batches
  • Custom compression presets

Development Setup

# Clone repository
git clone <repository-url>
cd image-converter

# Create development environment
python3 -m venv dev_env
source dev_env/bin/activate

# Install development dependencies
pip install -r requirements.txt
pip install pytest black flake8  # For testing and linting

📄 License

This script is provided as-is for educational and practical use. Feel free to modify and distribute according to your needs.

Dependencies

  • Pillow: PIL Software License (PIL license is compatible with GPL)
  • Python: Python Software Foundation License

Disclaimer

This software is provided "as is" without warranty of any kind. Users are responsible for testing with their specific use cases and ensuring backup of important files.


🔗 Quick Reference

Most Common Commands

# Basic conversion
python3 image_converter.py /path/to/images

# High quality
python3 image_converter.py /path/to/images -q 95

# Custom output
python3 image_converter.py /path/to/images -o /path/to/output

# Lossless
python3 image_converter.py /path/to/images --lossless

Support

For issues or questions, please refer to the troubleshooting section above or check the project documentation.


Last updated: 2024 - Version 1.0

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages