---
title: "Comment by Anjan kumar Sharma on \"Compressing and Cropping Images Without Losing Quality in Python\" | Hashnode"
description: "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 th"
url: "https://hashnode.com/posts/compressing-and-cropping-images-without-losing-quality-in-python/6687cd8ff32753482ee8aa30/comment/668afbce6b3b388beae552f7"
---

[Discussion](https://hashnode.com/posts/compressing-and-cropping-images-without-losing-quality-in-python/6687cd8ff32753482ee8aa30)

Comment [Compressing and Cropping Images Without Losing Quality in Python](https://hashnode.com/posts/compressing-and-cropping-images-without-losing-quality-in-python/6687cd8ff32753482ee8aa30)

[Anjan kumar Sharma](https://hashnode.com/@AnjanSharma)

[Jul 7, 2024](https://hashnode.com/posts/compressing-and-cropping-images-without-losing-quality-in-python/6687cd8ff32753482ee8aa30/comment/668afbce6b3b388beae552f7)

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.
