I'm working with thousands of large image files in a regularly updated library. The following script does the job (on average reduces my file size ~95%) but costs me around 25 seconds to compress one image. Obviously, I can just let the script run overnight, but it would be cool if I can shave some time off this process. I'm mostly looking for any unnecessary redundancies or overhead in the script that can be trimmed out to speed up the process. I'm still new to Python, so go easy on me.
from PIL import Image from pathlib import Path import os, sys import glob root_dir = "/.../" basewidth = 3500 for filename in glob.iglob(root_dir + '*.jpg', recursive=True): p = Path(filename) img = p.relative_to(root_dir) new_name = (root_dir + 'compressed/' + str(img)) print(new_name) im = Image.open(filename) wpercent = (basewidth/float(im.size)) hsize = int((float(im.size)*float(wpercent))) im = im.resize((basewidth,hsize), Image.ANTIALIAS) im.save(new_name, 'JPEG', quality=40)