When working with images, especially for web applications, it’s essential to balance quality and file size. Large images can slow down your website, leading to a poor user experience. Python provides several libraries that make it easy to compress an...
blog.bytescrum.com4 min read
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):
Open the input image
image = Image.open(input_image_path)
Resize the image to the target width and height
image = image.resize((target_width, target_height), Image.ANTIALIAS)
Save the resized image with high quality
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.