Skip to content

Instantly share code, notes, and snippets.

@vedranmarkulj vedranmarkulj/ Secret
Created Nov 4, 2018

What would you like to do?
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,
orig_image =
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), optimize=True, quality=100, format='png')
if file_bytes.tell() <= max_size:, 0)
with open(image_file, 'wb') as f_output:
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
You can’t perform that action at this time.