Created
November 25, 2017 05:53
-
-
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.
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage: