Write a Python script to batch convert images to different formats using Pillow.
- User
Write a Python script to batch convert images to different formats using Pillow.
Assistant
Considering Image Conversion
Okay, I'm thinking about the user's request for a Python script. My primary focus is understanding the image format conversion process. I'm zeroing in on the Pillow library as the key tool. I'm also now thinking about the specific requirements, such as file handling, error management, and user-friendly input. I think I'm nearly ready to start writing the skeleton of the script.
Drafting Code Structure
I've moved on to the actual code structure now. I'm focusing on the
batch_convertfunction, deciding on the parameters. I thinkinput_folder,output_folder, andtarget_formatmake the most sense. I've also figured out the internal steps: checking/creating the output folder, listing existing files, handling image validation (likely a file extension check), and mode conversion (especially for RGBA to RGB for JPEG). I'm confident about these steps.Addressing Edge Cases
I'm now zeroing in on robustness. I've successfully addressed the transparency issue with JPEGs. The script will now handle transparency correctly by converting to RGB where necessary before saving. Also, case-sensitive filename problems are gone with
os.path.splitext. I'm making it so users need a specific output folder. The code is taking form now. Printing progress is something I'll start next.Refining Image Processing
I'm now fully immersed in the nitty-gritty of image processing. I've integrated
try...exceptblocks to gracefully handle potential errors during image opening or saving. Within the loop, I'm focusing on the conversion, checking for transparency issues with PNGs, and ensuring quality for JPEGs usingquality=90. Now, file paths and formats are being precisely constructed. I can move on to testing now!Implementing User Feedback
I'm now focusing on user feedback and making the script more accessible. I'm adding a
mainblock to enable direct running.argparseis now integrated, enabling the user to specify input and output directories and target formats directly from the command line. This significantly enhances usability. I'm also preparing to add detailed comments and type hints for clarity. I will also make sure the user sees what's happening.Composing the Documentation
I'm now fully immersed in the explanatory aspect. I'm focusing on the user documentation. First, I will explain installing Pillow. Second, I will make sure I include instructions on running the script. Finally, I will clearly explain how transparency is handled in the conversion (i.e., RGBA to RGB for JPEGs). This documentation is essential to the overall project now.
Here is a complete, robust Python script to batch convert images using the Pillow library.
Prerequisites
You will need to install the Pillow library:
pip install PillowThe Python Script (
batch_convert.py)This script includes error handling and a specific fix for converting transparent images (like PNGs) to formats that don't support transparency (like JPEGs) by adding a white background.
import os from PIL import Image import sys def batch_convert_images(input_folder, output_folder, target_format, quality=85): """ Converts all images in input_folder to target_format and saves them to output_folder. :param input_folder: Path to the folder containing source images :param output_folder: Path to the folder where converted images will be saved :param target_format: Target extension (e.g., 'jpg', 'png', 'webp') :param quality: Quality setting for JPEG/WebP (0-100) """ # Ensure target format doesn't have a dot target_format = target_format.strip('.').lower() # Create output folder if it doesn't exist if not os.path.exists(output_folder): os.makedirs(output_folder) print(f"Created directory: {output_folder}") # Supported extensions to look for in the input folder valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp', '.gif') count = 0 errors = 0 print(f"Starting conversion to .{target_format} ...") for filename in os.listdir(input_folder): if filename.lower().endswith(valid_extensions): file_path = os.path.join(input_folder, filename) try: with Image.open(file_path) as img: # Get the file name without extension clean_name = os.path.splitext(filename)[0] new_filename = f"{clean_name}.{target_format}" save_path = os.path.join(output_folder, new_filename) # HANDLE TRANSPARENCY # If converting to a format that doesn't support alpha (like JPG), # convert RGBA to RGB with a white background. if target_format in ['jpg', 'jpeg', 'bmp'] and img.mode in ('RGBA', 'LA'): fill_color = (255, 255, 255) # White background background = Image.new(img.mode[:-1], img.size, fill_color) background.paste(img, img.split()[-1]) img = background.convert('RGB') # Ensure mode is compatible (e.g., converting P mode to RGB) elif img.mode != 'RGB' and target_format in ['jpg', 'jpeg']: img = img.convert('RGB') # Save the image if target_format in ['jpg', 'jpeg', 'webp']: img.save(save_path, quality=quality) else: img.save(save_path) print(f"Converted: {filename} -> {new_filename}") count += 1 except Exception as e: print(f"Error converting {filename}: {e}") errors += 1 print(f"\nDone! Converted {count} images. {errors} errors.") if __name__ == "__main__": # --- CONFIGURATION --- source_dir = "input_images" # Folder containing your original images dest_dir = "output_images" # Folder where new images will go format_to = "webp" # Desired format: 'png', 'jpg', 'webp', etc. # --------------------- # Check if source dir exists before running if os.path.exists(source_dir): batch_convert_images(source_dir, dest_dir, format_to) else: print(f"Error: Source directory '{source_dir}' not found.") print("Please create the folder or change the 'source_dir' variable.")How to use it
- Create folders: Create a folder named
input_imagesin the same directory as the script (or change thesource_dirvariable in the code). - Add images: Put the images you want to convert into that folder.
- Configure: Change the variable
format_toat the bottom of the script to your desired format (e.g.,'png','jpg','webp'). - Run:
python batch_convert.py
Key Features of this Script
- Transparency Handling:
- If you convert a transparent PNG to a JPEG, standard scripts will crash or result in a black background.
- This script detects if the input has transparency (
RGBA) and the output doesn't support it (JPG). It automatically creates a white background before saving.
- File Validation: It only attempts to process files with valid image extensions, ignoring text or system files in the folder.
- Auto-Directory Creation: It creates the output directory automatically if it doesn't exist.
- Quality Control: It accepts a
qualityparameter (defaults to 85) which is useful for reducing file size when converting to JPG or WebP.
- Create folders: Create a folder named
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.