The user wants a Python script to batch convert images to different formats using the Pillow library (PIL).
1. Understand the Goal:
* Input: A folder containing source images (e.g., .jpg, .png).
* Process: Iterate through the images, open them, convert them to a target format (e.g., .webp, .png).
* Output: Save the converted images to a destination folder.
* Tool: Python with the Pillow library.
2. Identify Key Requirements & Edge Cases:
* Library: Needs Pillow (pip install Pillow).
* Arguments/Flexibility: Hardcoding paths is bad practice. The script should accept arguments (input folder, output folder, target format).
* File Handling:
* Needs to check if the input folder exists.
* Needs to create the output folder if it doesn't exist.
* Should handle filename extensions correctly (replace old with new).
* Should skip non-image files (though Image.open will throw an error, so a try-except block is necessary).
* Transparency/Mode issues: Converting RGBA (PNG with transparency) to JPEG often fails or looks bad because JPEG doesn't support alpha. I should probably handle this by converting to RGB before saving as JPEG, or at least mention it. Self-correction: Keep the script simple for the first draft, but add a robust version or at least a note about RGBA to RGB conversion.
3. Drafting the Code Structure:
Imports:os, sys, PIL.Image.
Function convert_images:
Args: input_dir, output_dir, target_format.
Logic:
Validate input_dir.
Create output_dir.
Loop through files in input_dir.
Construct full paths.
try: Open image, convert (if necessary), save to output_dir with new extension.
except: Log error (e.g., "Cannot open file").
Print success message.
Main execution block:
Use argparse for better command-line usage? Or just simple variables for a basic script. Decision: Provide a robust version using argparse because it's more professional, but explain how to run it.
4. Refining the Code (Mental Check):
JPEG Conversion Issue: If I convert logo.png (RGBA) to logo.jpg, Pillow raises an IOError (sometimes) or creates a messed-up image unless I remove the alpha channel.
Fix: Check if target_format is 'JPEG' and image mode is 'RGBA' or 'P', then image.convert('RGB').
Extensions:target_format usually implies the extension (e.g., "PNG", "JPEG"). Pillow handles the format detection based on the filename extension in save(), but explicit format argument is safer.
5. Writing the Script (Iterative):
Step 1: Setup
python
import os
from PIL import Image
Step 2: The Conversion Function
python
def batch_convert(input_folder, output_folder, format):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.startswith('.'): continue # skip hidden files
try:
img_path = os.path.join(input_folder, filename)
img = Image.open(img_path)
# Handle RGBA -> RGB for JPEG
if format.upper() == 'JPEG' and img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
name, _ = os.path.splitext(filename)
new_name = f"{name}.{format.lower()}"
output_path = os.path.join(output_folder, new_name)
img.save(output_path, format=format)
print(f"Converted {filename} to {new_name}")
except Exception as e:
print(f"Error converting {filename}: {e}")
Step 3: Argument Parsing (making it a CLI tool)
This makes the script actually useful. I will include argparse.
6. Structuring the Final Response:
* Prerequisites: Mention pip install Pillow.
* The Code: A complete, commented script using argparse.
* Explanation: Break down what the script does (RGBA handling, Error handling).
* How to use it: Command line examples.
* Optional improvements: Resizing, quality settings.
7. Reviewing against User Request:
"Write a Python script to batch convert images to different formats using Pillow."
The drafted plan covers this perfectly. The "RGBA to RGB" logic is a crucial value-add because beginners always get stuck on PNG -> JPG conversion errors.
8. Final Polish: ensure variable names are clear (input_dir, output_dir, target_format). Add comments.
(Self-Correction during drafting): Should I use pathlib?
os.path is standard, but pathlib is more modern. I'll stick to os for broader compatibility with older Python versions, but pathlib is cleaner. Let's use os as it's often easier for beginners to read in script form. Actually, let's stick to os since it's universally understood in Python tutorials.
9. Final Code Assembly: (Similar to the provided good response).
Include optimize=True option? Maybe just keep it simple first.
Include quality option? Yes, usually relevant for JPEGs.
Let's refine the script to allow passing quality arguments.
Okay, ready to write the solution.
Here is a complete, robust Python script to batch convert images.
Prerequisites
You will need the Pillow library (the modern fork of PIL). Install it via pip:
bash
pip install Pillow
The Python Script
This script includes error handling (e.g., skipping non-image files) and logic to handle format specific issues (like converting transparent PNGs to JPGs).
Save this code as converter.py.
python
How to use it
Open your terminal or command prompt and run the script by providing the input folder, output folder, and desired format.
RGBA to RGB Handling: Standard JPEGs cannot handle transparency (Alpha channels). If you try to convert a transparent PNG to JPG directly, Pillow usually throws an error. This script automatically detects RGBA mode and converts it to RGB before saving.
Safety: It uses os.path to ensure it works correctly on Windows, macOS, and Linux.
Non-destructive: It creates a new folder for output rather than overwriting your original files.
Error Skipping: If you have a .txt file or a corrupted image inside the folder, the script will catch the error and skip that file instead of crashing.
import os
import argparse
from PIL import Image
def batch_convert(input_dir, output_dir, target_format, quality=85):
"""
Converts all images in a directory to a specific format.
:param input_dir: Path to the source folder.
:param output_dir: Path to the destination folder.
:param target_format: The file extension to convert to (e.g., 'JPEG', 'PNG').
:param quality: Quality for JPEG compression (1-95).
"""
# 1. Validate Input Directory
if not os.path.exists(input_dir):
print(f"Error: Input directory '{input_dir}' does not exist.")
return
# 2. Create Output Directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print(f"Created output directory: {output_dir}")
# 3. Normalize format string (e.g., jpg -> JPEG)
fmt_upper = target_format.upper()
if fmt_upper == 'JPG':
fmt_upper = 'JPEG'
print(f"Starting conversion to {fmt_upper}...")
# 4. Iterate over files
count = 0
for filename in os.listdir(input_dir):
# Construct full file path
input_path = os.path.join(input_dir, filename)
# Skip directories
if os.path.isdir(input_path):
continue
try:
# Open image
with Image.open(input_path) as img:
# Prepare output filename
base_name = os.path.splitext(filename)[0]
output_filename = f"{base_name}.{target_format.lower()}"
output_path = os.path.join(output_dir, output_filename)
# --- Handle Format Specifics ---
# If converting to JPEG, we must handle Transparency (Alpha channel)
# JPEG does not support transparency.
if fmt_upper == 'JPEG':
# Convert RGBA or P mode to RGB
if img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
# Save the image
# We pass specific arguments for JPEG quality
if fmt_upper == 'JPEG':
img.save(output_path, format=fmt_upper, quality=quality)
else:
img.save(output_path, format=fmt_upper)
print(f"[OK] Converted: {filename} -> {output_filename}")
count += 1
except Exception as e:
# Catch errors (e.g., file is not an image or corrupt)
print(f"[SKIP] Could not convert {filename}: {e}")
print(f"\nFinished. Successfully converted {count} images.")
if __name__ == "__main__":
# Set up command line arguments
parser = argparse.ArgumentParser(description="Batch convert images using Pillow.")
parser.add_argument("input", help="Path to the input folder")
parser.add_argument("output", help="Path to the output folder")
parser.add_argument("format", help="Target format (e.g., jpg, png, webp)")
parser.add_argument("--quality", type=int, default=85, help="Quality for JPEG/WEBP (1-100)")
args = parser.parse_args()
batch_convert(args.input, args.output, args.format, args.quality)