- Given an image stored at
- a target
heightin pixels, and
- a target starting point (upper-left)
yin 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:
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
height=190 pixels and upper-left starting points
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:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.