Skip to content

Instantly share code, notes, and snippets.

@jairajsahgal
Created September 30, 2023 18:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jairajsahgal/c1b66ec9d51f470c6afe347e3fda967a to your computer and use it in GitHub Desktop.
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.
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)
@2h311
Copy link

2h311 commented Oct 2, 2023

pillow?

@jairajsahgal
Copy link
Author

Yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment