Sign in
Log inSign up
ByteScrum Technologies

82 likes

·

590 reads

1 comment

Anjan kumar Sharma
Anjan kumar Sharma
Jul 7, 2024

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:

  • Replace "input.jpg" with the path to your input image file.
  • Replace "output.jpg" with the desired path for the output compressed and cropped image.
  • Adjust target_width and target_height to specify the dimensions for the cropped image.

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.

1
·