Skip to content

Instantly share code, notes, and snippets.

@aljiwala
Created November 25, 2017 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aljiwala/bd6e9c2156b45823ef1c01b571d63cbb to your computer and use it in GitHub Desktop.
Save aljiwala/bd6e9c2156b45823ef1c01b571d63cbb to your computer and use it in GitHub Desktop.
Compress the size of the given file with the particular `scale` until `max_size` limit is achieved.
from PIL import Image
from io import BytesIO
def compress_image(original_file, max_size, scale):
"""
It should compress the size of the given file with the particular `scale`
until `max_size` limit is achieved.
"""
assert(0.0 < scale < 1.0)
orig_image = Image.open(original_file)
cur_size = orig_image.size
while True:
cur_size = (int(cur_size[0] * scale), int(cur_size[1] * scale))
resized_file = orig_image.resize(cur_size, Image.ANTIALIAS)
with BytesIO() as file_bytes:
resized_file.save(file_bytes, optimize=True, quality=95, format='jpeg')
if file_bytes.tell() <= max_size:
file_bytes.seek(0, 0)
with open(original_file, 'wb') as f_output:
f_output.write(file_bytes.read())
break
@aljiwala
Copy link
Author

Sample usage:

compress_image(
    original_file=file_name,
    max_size=MAX_ALLOWED_MEDIA_SIZE,
    scale=0.9
)

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