To crop an image using Python Imaging Library (PIL), you need to use the ‘crop’ function. This function requires a tuple specifying the left, upper, right, and lower pixel coordinate. The syntax is: Image.crop((left, upper, right, lower)).
Here’s a simple script:
from PIL import Image
def crop_image(input_image, output_image, start_left, start_upper, end_right, end_lower):
img = Image.open(input_image)
cropped_img = img.crop((start_left, start_upper, end_right, end_lower))
cropped_img.save(output_image)
crop_image('input.jpg', 'output.jpg', 100, 100, 400, 400)
In this script, we first import the Image module from PIL. We define a function called ‘crop_image’. It takes six parameters: input_image, output_image, start_left, start_upper, end_right, and end_lower. Inside the function, we open the image with Image.open(), then call the ‘crop’ method on the opened image object, passing in a tuple of coordinates. Finally, we save the cropped image with the ‘save’ method.