0
0
PythonHow-ToBeginner · 3 min read

How to Crop Image in Python: Simple Guide with Examples

To crop an image in Python, use the Pillow library's crop() method on an Image object. You provide a box tuple (left, upper, right, lower) defining the crop area, and it returns the cropped image.
📐

Syntax

The crop() method is called on an Image object from the Pillow library. It takes one argument: a tuple defining the crop rectangle as (left, upper, right, lower). These values are pixel coordinates.

  • left: The x-coordinate of the left edge of the crop box.
  • upper: The y-coordinate of the top edge of the crop box.
  • right: The x-coordinate of the right edge of the crop box.
  • lower: The y-coordinate of the bottom edge of the crop box.

The method returns a new Image object cropped to this box.

python
cropped_image = image.crop((left, upper, right, lower))
💻

Example

This example opens an image file, crops a 100x100 pixel square from the top-left corner, and saves the cropped image.

python
from PIL import Image

# Open an image file
image = Image.open('example.jpg')

# Define the crop box (left, upper, right, lower)
crop_box = (0, 0, 100, 100)

# Crop the image
cropped_image = image.crop(crop_box)

# Save the cropped image
cropped_image.save('cropped_example.jpg')

print('Image cropped and saved as cropped_example.jpg')
Output
Image cropped and saved as cropped_example.jpg
⚠️

Common Pitfalls

  • Using coordinates outside the image bounds causes unexpected results or errors.
  • Remember the coordinate system starts at (0, 0) in the top-left corner.
  • Passing the crop box in the wrong order (e.g., mixing up left and right) will crop the wrong area.
  • Not saving or displaying the cropped image means changes are lost.
python
from PIL import Image

image = Image.open('example.jpg')

# Wrong: coordinates outside image size
# crop_box = (0, 0, 10000, 10000)  # May cause error or unexpected crop

# Correct: crop box within image size
crop_box = (0, 0, 100, 100)
cropped_image = image.crop(crop_box)
cropped_image.save('correct_crop.jpg')
📊

Quick Reference

Remember these tips when cropping images in Python:

  • Use Pillow library's crop() method.
  • Coordinates are in pixels, starting at top-left (0, 0).
  • Crop box format: (left, upper, right, lower).
  • Always save or display the cropped image to see results.

Key Takeaways

Use Pillow's Image.crop() method with a box tuple to crop images in Python.
Coordinates start at (0, 0) in the top-left corner of the image.
Ensure crop box coordinates are within the image size to avoid errors.
Save or display the cropped image to keep the changes.
The crop box tuple format is (left, upper, right, lower).