Crop an image with Python and Pillow
Keep a 400 × 300 region starting 100 pixels from the left and 50 pixels from the top.
View code and setup
Before you start
- Install Python 3 with virtual-environment support.
- Put a copy of your image in a working folder. Use the input filename shown in the script, or change it to match your file.
- Run the setup commands for your operating system to install Pillow in a local .venv.
- Save the Python code as convert_image.py in the same folder, then run it with the command for your operating system.
- The script saves a new image. Change the output filename before running if you want to keep an earlier result.
python3 -m venv .venv
.venv/bin/python -m pip install Pillowpy -3 -m venv .venv
.venv\Scripts\python.exe -m pip install Pillowfrom PIL import Image, ImageOps
with Image.open("input.png") as source:
if getattr(source, "n_frames", 1) != 1:
raise ValueError("Choose a single still image")
image = ImageOps.exif_transpose(source).convert("RGBA")
left, top, width, height = 100, 50, 400, 300
if left + width > image.width or top + height > image.height:
raise ValueError("Choose a crop within the oriented image")
cropped = image.crop((left, top, left + width, top + height))
cropped.save("cropped.png").venv/bin/python convert_image.py.venv\Scripts\python.exe convert_image.pyLimits and output
- Coordinates are measured from the top-left after EXIF orientation is applied. Change the rectangle to fit your image.
- Cropping removes outside pixels without resizing the retained region. This example uses 8-bit RGBA and does not preserve all metadata.
Documentation: Pillow image operations; Pillow tutorial and installation