Skip to content

Instantly share code, notes, and snippets.

@vedranmarkulj
Created November 4, 2018 20:16
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 vedranmarkulj/097117a0fce359188b1aee38e13f43f6 to your computer and use it in GitHub Desktop.
Save vedranmarkulj/097117a0fce359188b1aee38e13f43f6 to your computer and use it in GitHub Desktop.
Post - Optimise Python code for data preparation using Concurrent features
from PIL import Image
from io import BytesIO
def compress_image(image_file, max_size=4000, max_dim=150, dim_diff_w=0, dim_diff_h=0, orig_image_w=None, orig_image_h=None):
print_values = {
'max_size': max_size,
'max_dim': max_dim,
'dim_diff_w': dim_diff_w,
'dim_diff_h': dim_diff_h,
'orig_image_w': orig_image_w,
'orig_image_h': orig_image_h,
}
print(print_values)
orig_image = Image.open(image_file)
orig_image_w, orig_image_h = orig_image.size
if orig_image_w > max_dim:
dim_diff_w = orig_image_w - max_dim
orig_image_w = max_dim
orig_image_h = orig_image_h - dim_diff_w
if orig_image_h > max_dim:
dim_diff_h = orig_image_h - max_dim
orig_image_h = max_dim
orig_image_w = orig_image_w - dim_diff_h
with BytesIO() as file_bytes:
if dim_diff_h + dim_diff_w > 0 or file_bytes.tell() >= max_size:
resize_image = orig_image.resize((orig_image_w, orig_image_h), Image.ANTIALIAS)
resize_image.save(file_bytes, optimize=True, quality=100, format='png')
if file_bytes.tell() <= max_size:
file_bytes.seek(0, 0)
with open(image_file, 'wb') as f_output:
f_output.write(file_bytes.read())
else:
new_max_dim = round(max_dim - (max_dim * 0.10))
compress_image(image_file, max_size=max_size, max_dim=new_max_dim, dim_diff_w=0, dim_diff_h=0,
orig_image_w=orig_image_w, orig_image_h=orig_image_h)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment