Skip to content

Useful tools

To compress images in a folder : Python script to compress images

Source : Article How to compress images using python and pil written by avanishcodes https://www.geeksforgeeks.org/how-to-compress-images-using-python-and-pil/

Result : automatisation of image compression

I modified the code of avanishcodes to adapt to my situation

# run this in any directory 
# add -v for verbose 
# get Pillow (fork of PIL) from 
# pip before running --> 
# pip install Pillow 

# import required libraries 
import os 
import sys 
import time
from PIL import Image 


def timing(func):
    """
    Mesure le temps d'exécution d'une fonction.
    """
    def wrapper(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        end_time = time.time()
        print("Run time : {:1.3}m".format(end_time - start_time))


    return wrapper

# define a function for 
# compressing an image 
def compressMe(folderpath, file, verbose = False): 

    # Get the path of the image
    filepath = os.path.join(folderpath, file) 

    print(filepath)

    # open the image 
    picture = Image.open(filepath) 

    # Save the picture with desired quality 
    # To change the quality of image, 
    # set the quality variable at 
    # your desired level, The more 
    # the value of quality variable 
    # and lesser the compression 
    picture.save(os.path.join(folderpath, "cmp_"+file), 
                "JPEG", 
                optimize = True, 
                quality = "web_medium") 
    return

# Define a main function 
@timing
def main():
    verbose = False

    # checks for verbose flag 
    if (len(sys.argv)>1): 

        if (sys.argv[1].lower()=="-v"): 
            verbose = True

    # finds current working dir 
    cwd = os.getcwd() 

    # the formats to consider
    formats = ('.jpg', '.jpeg') 

    # Get liste of folders
    liste_dir = os.listdir(cwd)

    # Remove the python script from the list of folder's name
    liste_dir.remove('compress.py')

    # Create an empty set to store the compressed images
    already_compressed = ""

    # Number of compressed images
    nb = 0

    # for each folder in this current working directory
    for folder in liste_dir:
        # get the folder's path
        cfold = os.getcwd()+"\\"+folder

        # for each file in this folder
        for file in os.listdir(cfold): 
            imgname, extension = (os.path.splitext(file)[0], os.path.splitext(file)[1].lower())

            #If the image's format is JPG or JPEG
            if extension in formats:

                # If the image is a compressed image
                if imgname.startswith("cmp_") and len(already_compressed)==0:
                    already_compressed += file
                # If not already compressed
                elif(already_compressed.find(file) == -1) and not(imgname.startswith("b")): 
                    # compress the image
                    compressMe(cfold, file, verbose) 
                    nb += 1

    print("Done") 
    print("Compressed: ", nb, " images")

# Driver code 
if __name__ == "__main__": 
    main()