Created
September 30, 2023 18:58
-
-
Save jairajsahgal/c1b66ec9d51f470c6afe347e3fda967a to your computer and use it in GitHub Desktop.
This method is used to compress an image and return the image object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def compress_image(image): | |
# Define your compression settings here | |
# For example, you can resize the image and adjust the quality | |
max_size = (800, 800) | |
quality = 80 | |
# Resize the image while preserving aspect ratio | |
image.thumbnail(max_size, Image.ANTIALIAS) | |
# Convert the image to RGB mode (necessary for saving as JPEG) | |
if image.mode != 'RGB': | |
image = image.convert('RGB') | |
# Save the compressed image to an in-memory buffer | |
compressed_image_io = BytesIO() | |
image.save(compressed_image_io, format='JPEG', quality=quality) | |
return Image.open(compressed_image_io) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pillow?