🖼️ Image Conversion Tool Guide
Batch WebP Converter with Size Optimization
Last Updated: August 3, 2025 | Version 1.0
📋 Overview
This Python script converts JPG/PNG images to WebP format while targeting specific file sizes (100-150 KB). Perfect for optimizing web assets while maintaining quality.
✨ Key Features:
Batch conversion of entire folders
Automatic quality adjustment to hit target file sizes
Support for JPG, JPEG, and PNG input formats
Customizable compression settings
🚀 Quick Start
1 Install Python
Download Python 3.8+ from [Link]/downloads
python --version # Should show Python 3.8+
2 Install Required Library
pip install pillow
3 Save the Script
Create a file named image_optimizer.py and copy the script below.
💻 Complete Script
📋 Copy-Paste Ready: The code below is properly formatted and ready to copy directly into your image_optimizer.py file.
from PIL import Image
import os
def convert_to_webp(input_path, output_path=None, target_size_kb=150, min_quality=30, max_quality=95):
"""
Converts an image to .webp format while targeting a specific file size.
Args:
input_path (str): Path to source image (JPG/PNG).
output_path (str): Optional output path. Default: same directory as source.
target_size_kb (int): Target file size in KB (default: 150).
min_quality (int): Minimum compression quality (default: 30).
max_quality (int): Starting compression quality (default: 95).
"""
if not input_path.lower().endswith(('.jpg', '.jpeg', '.png')):
print(f"Skipping unsupported file: {input_path}")
return
if output_path is None:
output_path = [Link](input_path)[0] + ".webp"
try:
with [Link](input_path) as img:
quality = max_quality
while quality >= min_quality:
[Link](output_path, "WEBP", quality=quality)
size_kb = [Link](output_path) / 1024
if size_kb <= target_size_kb:
print(f"✅ {input_path} → {output_path} ({int(size_kb)} KB at quality {quality})")
return
quality -= 5
print(f"⚠️ {input_path} could not be compressed under {target_size_kb} KB. Final size: {int(size_kb)} KB")
except Exception as e:
print(f"❌ Failed to convert {input_path}: {e}")
def batch_convert(folder_path, target_size_kb=150):
"""
Converts all JPG/PNG images in a folder to .webp.
Args:
folder_path (str): Path to folder containing images.
target_size_kb (int): Target file size per image (default: 150 KB).
"""
for filename in [Link](folder_path):
input_file = [Link](folder_path, filename)
if [Link](input_file):
convert_to_webp(input_file, target_size_kb=target_size_kb)
# EXAMPLE USAGE:
# convert_to_webp("unoptimized_image.jpg", target_size_kb=120)
# batch_convert("./project_assets/", target_size_kb=150)
📖 Usage Examples
Single Image Conversion
# Basic conversion convert_to_webp("[Link]", target_size_kb=130) # Custom output location convert_to_webp("[Link]", "optimized/[Link]") # With custom quality settings convert_to_webp("large_image.jpg", target_size_kb=100, min_quality=40)
Batch Conversion
# Convert all images in a folder batch_convert("/path/to/your/images/", target_size_kb=140) # Convert current directory images batch_convert("./", target_size_kb=120)
💡 Pro Tip: Always backup your original images before running batch operations!
⚙️ Configuration Parameters
Parameter Description Default Recommended Range
target_size_kb Maximum file size in KB 150 100-200
min_quality Lowest quality before aborting 30 20-50
max_quality Starting compression quality 95 80-95
🔧 Troubleshooting
Error Message Cause Solution
ModuleNotFoundError: PIL Pillow library not installed Run pip install pillow
PermissionError No write access to output directory Check folder permissions or run as administrator
Skipping unsupported file File format not supported Only JPG, JPEG, PNG are supported
Could not be compressed under X KB Image too complex for target size Increase target_size_kb or lower min_quality
⚠️ Common Issues:
Very small images might not compress much further
Images with transparency (PNG) may have larger file sizes
Extremely detailed images might need higher target sizes
📝 Best Practices
File Size Guidelines
Hero Images: 150-200 KB
Product Photos: 100-150 KB
Thumbnails: 50-100 KB
Icons/Small Graphics: 20-50 KB
Quality vs. Size Balance
Start with target_size_kb=150 for most web images
Use min_quality=30 to prevent over-compression
Test different settings on sample images first
Consider using [Link] for manual fine-tuning
Workflow Recommendations
1. Create a backup of original images
2. Test script on a few sample images
3. Adjust parameters based on results
4. Run batch conversion on entire folder
5. Review output quality and file sizes
🎯 Advanced Usage
Custom Script Integration
# Add to your build process
import subprocess
import sys
def optimize_project_images():
"""Optimize all images in project directories"""
directories = ["./src/assets/", "./public/images/"]
for directory in directories:
if [Link](directory):
print(f"Processing {directory}...")
batch_convert(directory, target_size_kb=130)
else:
print(f"Directory not found: {directory}")
# Run optimization
if __name__ == "__main__":
optimize_project_images()
Automated Quality Reporting
def convert_with_report(input_path, target_size_kb=150):
"""Convert image and return size reduction report"""
original_size = [Link](input_path) / 1024
convert_to_webp(input_path, target_size_kb=target_size_kb)
webp_path = [Link](input_path)[0] + ".webp"
if [Link](webp_path):
new_size = [Link](webp_path) / 1024
savings = ((original_size - new_size) / original_size) * 100
print(f"💾 Size reduction: {savings:.1f}% ({original_size:.1f} → {new_size:.1f} KB)")
Need Help?
Contact: bishowkarmabishnu2024@[Link] | Internal Support: #dev-tools
Generated on August 3, 2025 | Asset Optimization Tool