Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Easy Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Requires third-party packages — install first
pip install Pillow

Python code

20 lines
Python 3.9+
from 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

stdout
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

  1. Use `img.convert('RGB')` before saving to JPEG to remove alpha channels.
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Files & data

Related tutorials and quizzes for this topic.