Implementing command-line options
I'm considering adding argparse for handling input, output, and format options. I'll also include an optional --quality for JPEG/WEBP files. It's fine to overwrite existing files, but I want to check with if dst_file.exists() and not args.overwrite. I’ll add the standard if __name__ == "__main__": for clarity.
I think it’s essential to include instructions on installing Pillow and usage examples like python batch_convert.py ./input ./output png. I want to keep the explanation minimal but effective. Let's finalize that! Below is a complete Python script that batch-converts images in a folder to another format using Pillow.
#!/usr/bin/env python3
"""
Batch convert images to a different format using Pillow.
Usage:
python batch_convert_images.py INPUT_DIR OUTPUT_DIR FORMAT [--quality 90] [--overwrite]
Example:
python batch_convert_images.py ./input ./output png
python batch_convert_images.py ./input ./output jpeg --quality 85
"""
import argparse
from pathlib import Path
from PIL import Image
def convert_image(src_path: Path, dst_path: Path, target_format: str, quality: int | None = None):
target_format = target_format.upper()
with Image.open(src_path) as im:
# Convert modes that JPEG doesn't support (no alpha channel)
if target_format in {"JPEG", "JPG"} and im.mode in ("RGBA", "P", "LA"):
im = im.convert("RGB")
dst_path.parent.mkdir(parents=True, exist_ok=True)
save_kwargs = {}
if quality is not None and target_format in {"JPEG", "JPG", "WEBP"}:
save_kwargs["quality"] = quality
im.save(dst_path, target_format, **save_kwargs)
def main():
parser = argparse.ArgumentParser(description="Batch convert images to another format using Pillow.")
parser.add_argument("input_dir", type=Path, help="Input directory containing images.")
parser.add_argument("output_dir", type=Path, help="Output directory for converted images.")
parser.add_argument("format", help="Target format (e.g. png, jpeg, webp, tiff).")
parser.add_argument(
"--quality",
type=int,
default=None,
help="Quality for lossy formats (JPEG/WEBP), e.g. 85. Optional."
)
parser.add_argument(
"--overwrite",
action="store_true",
help="Overwrite existing files in the output directory."
)
args = parser.parse_args()
input_dir: Path = args.input_dir
output_dir: Path = args.output_dir
target_format: str = args.format
if not input_dir.is_dir():
raise SystemExit(f"Input directory does not exist or is not a directory: {input_dir}")
output_dir.mkdir(parents=True, exist_ok=True)
# Basic list of image extensions; adjust as needed
exts = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tif", ".tiff", ".webp", ".heic", ".heif"}
count = 0
for src_path in input_dir.iterdir():
if not src_path.is_file():
continue
if src_path.suffix.lower() not in exts:
continue
dst_filename = src_path.stem + "." + target_format.lower()
dst_path = output_dir / dst_filename
if dst_path.exists() and not args.overwrite:
print(f"Skipping (exists): {dst_path}")
continue
try:
convert_image(src_path, dst_path, target_format, quality=args.quality)
print(f"Converted: {src_path.name} -> {dst_path.name}")
count += 1
except Exception as e:
print(f"Error converting {src_path}: {e}")
print(f"Done. Converted {count} file(s).")
if __name__ == "__main__":
main()
Setup
- Install Pillow:
pip install pillow
-
Save the script as batch_convert_images.py.
-
Run:
python batch_convert_images.py ./input ./output png
# or
python batch_convert_images.py ./input ./output jpeg --quality 85 --overwrite
If you want it to recurse into subdirectories or support more options, I can extend the script.