How to Convert Images Between Formats in Python
Use the Pillow library to open an image from one file format and save it to another, with error handling for missing files or conversion issues.
pip install Pillow
Python code
20 linesfrom PIL import Image
import sys
def convert_image_format(input_path, output_path):
try:
img = Image.open(input_path)
img.save(output_path)
print(f"Converted {input_path} to {output_path}")
except FileNotFoundError:
print(f"Error: File {input_path} not found")
sys.exit(1)
except Exception as e:
print(f"Error converting image: {e}")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python convert_image.py input.png output.jpg")
sys.exit(1)
convert_image_format(sys.argv[1], sys.argv[2])
Output
Converted input.png to output.jpg
How it works
The Image.open() loads the image into memory as an object, regardless of its original format. Calling .save(output_path) determines the output format from the file extension in the path string. Pillow supports common formats like PNG, JPEG, BMP, GIF, and TIFF. The try/except blocks catch missing files and any conversion errors (e.g., unsupported mode for JPEG), ensuring the script exits gracefully with a clear message.
Common mistakes
- Forgetting to install Pillow with `pip install Pillow` before running the script.
- Assuming all image modes (e.g., RGBA) can be saved to JPEG without conversion first.
- Providing an output filename with an unrecognized extension, causing a `KeyError` in Pillow.
Variations
- Use `img.convert('RGB')` before saving to JPEG to remove alpha channels.
- Loop over multiple files using `glob.glob('*.png')` for batch conversion.
Real-world use cases
- Resizing and converting user-uploaded profile pictures from PNG to JPEG for standardized storage.
- Transforming screenshots from PNG to JPEG before embedding them into documentation to reduce file size.
- Converting image assets from TIFF to PNG in a data pipeline that requires consistent input formats.
Sponsored
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert CSV Files to JSON in Python easy
- Convert Image to ASCII Art in Python medium
Keep learning
Related tutorials and quizzes for this topic.