To compress and crop images without losing quality in Python, you can use the Pillow library. Here's an example code snippet that demonstrates how to achieve this:
from PIL import Image
def compress_and_crop_image(input_image_path, output_image_path, target_width, target_height):
image = Image.open(input_image_path)
image = image.resize((target_width, target_height), Image.ANTIALIAS)
image.save(output_image_path, quality=95)
if name == "main": input_image_path = "input.jpg" output_image_path = "output.jpg" target_width = 500 target_height = 500
compress_and_crop_image(input_image_path, output_image_path, target_width, target_height)
In this code snippet:
This code snippet resizes the input image to the specified dimensions using bilinear interpolation (Image.ANTIALIAS) to maintain quality. It then saves the resized image with high quality (quality=95) to reduce file size without significant loss of quality.