Python3

Python script: Image Resizer and Cropper (using Pillow library)


from PIL import Image

def resize_image(input_image_path, output_image_path, size):
original_image = Image.open(input_image_path)
width, height = original_image.size
resized_image = original_image.resize(size)
resized_image.save(output_image_path)

def crop_image(input_image_path, output_image_path, crop_box):
original_image = Image.open(input_image_path)
cropped_image = original_image.crop(crop_box)
cropped_image.save(output_image_path)

# Example of resizing an image
input_image_path = "input.jpg"
output_image_path = "resized_image.jpg"
size = (300, 300)
resize_image(input_image_path, output_image_path, size)

# Example of cropping an image
input_image_path = "input.jpg"
output_image_path = "cropped_image.jpg"
crop_box = (100, 100, 400, 400) # (left, upper, right, lower)
crop_image(input_image_path, output_image_path, crop_box)

Python script above demonstrates how to resize and crop images using the Pillow library. The script defines two functions: `resize_image` for resizing an image and `crop_image` for cropping an image.

– The `resize_image` function takes the input image path, output image path, and the desired size as parameters. It opens the original image, resizes it to the specified size, and saves the resized image to the output path.

– The `crop_image` function takes the input image path, output image path, and the crop box as parameters. It opens the original image, crops the image based on the provided box coordinates, and saves the cropped image to the output path.

In the example provided in the script:
1. An image named “input.jpg” is resized to a size of 300×300 pixels and saved as “resized_image.jpg”.
2. Another image “input.jpg” is cropped using a crop box of (100, 100, 400, 400) and saved as “cropped_image.jpg”.

This script showcases how to perform basic image manipulation tasks like resizing and cropping using the Pillow library in Python.