How to Crop an Image Using PIL?

Problem Formulation

  • Given an image stored at image.jpeg,
  • a target width and height in pixels, and
  • a target starting point (upper-left) x and y in the coordinate system.

How to crop the given image in Python PIL so that the resulting image has width * height size?

Here’s an example of how the original image is cropped to a smaller area from (100, 20) upper-left to (540, 210) bottom-right:

How to Crop an Image Using PIL?

Solution: img.crop()

To crop an image to a certain area, use the PIL function Image.crop(left, upper, right, lower) that defines the area to be cropped using two points in the coordinate system: (left, upper) and (right, lower) pixel values. Those two points unambiguously define the rectangle to be cropped.

Here’s the example of how to crop an image with width=440 and height=190 pixels and upper-left starting points x=100 and y=20 pixels as shown in the graphic before.

from PIL import Image

# Given information
img = Image.open("image.jpg")
width, height = 440, 190
x, y = 100, 20

# Select area to crop
area = (x, y, x+width, y+height)

# Crop, show, and save image
cropped_img = img.crop(area)
cropped_img.show()
cropped_img.save("cropped_image.jpg")

You can play around with this example—including the original and cropped images shown here—in our interactive playground:

Click to run code.

Here’s the original image:

image.jpg

And here’s the cropped image:

cropped_image.jpg

Do you want to stay at the top of the game in Python? Join our free email academy and download your Python cheat sheets now: