Computer >> Computer tutorials >  >> Programming >> Python

Cropping an image using the Pillow library


In this program, we will crop an image using the Pillow library. We will use the crop() function for the same. The function takes left, top, right, bottom pixel coordinates to crop the image.

Original Image

Cropping an image using the Pillow library

Algorithm

Step 1: Import Image from Pillow.
Step 2: Read the image.
Step 3: Crop the image using the crop function.
Step 4: Display the output.

Example Code

from PIL import Image

im = Image.open('testimage.jpg')
width, height = im.size

left = 5
top = height / 2
right = 164
bottom = 3 * height / 2

im1 = im.crop((left, top, right, bottom))
im1.show()

Output

Cropping an image using the Pillow library