Problem Formulation
- Given an image stored at
image.jpeg
, - a target
width
andheight
in pixels, and - a target starting point (upper-left)
x
andy
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:
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:
Here’s the original image:
And here’s the cropped image:
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: