Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save noahdominic/3c4853bc5b41ff3389b12717caed7f0e to your computer and use it in GitHub Desktop.
Save noahdominic/3c4853bc5b41ff3389b12717caed7f0e to your computer and use it in GitHub Desktop.

Automated Image Compression for Web Development with Python

In web development, the performance of a website is a crucial factor that can significantly impact UX. One effective way to optimise a website is by compressing images to reduce their file size. To streamline this process for my personal projects, I've created a Python script that automates image compression and organisation. This may be of use to you.

Script Overview:

This Python script performs the following tasks:

  1. Searches for image files in the current directory,

  2. Resizes images to various predefined widths (100px, 300px, 512px, 1024px, 2048px, and the original 'max-res' width) at various predefined quality settings (100px at 50%, 300px at 75%, 512px at 85%, 1024px at 95%, 2048px at 95%, and 'max-res' at 98%),1

  3. and Organises the compressed images into separate folders based on their widths.

Usage:

  1. Install the Pillow library:

    pip install pillow
  2. Write this script into a file (in this case, we use the name process_images).

  3. In the directory with all the images, run with this command:

$  python process_images

The script

Customisation:

  • The list of supported file extensions are stored in the file_extensions variable to make cusomisation easier, allowing the inclusion of more image formats.
  • The output folder names and quality settings in the output_folders dictionary allows this script to be easily rewritten for other project specifications.

Here is the script in its entirety.

import os
from PIL import Image

# Define the output folders and their corresponding width and quality settings
output_folders = {
    "100": {"width": 100, "quality": 50},
    "300": {"width": 300, "quality": 75},
    "512": {"width": 512, "quality": 85},
    "1024": {"width": 1024, "quality": 95},
    "2048": {"width": 2048, "quality": 95},
    "max-res": {"width": None, "quality": 98}
}

# File extensions
file_extensions = (".jpg", ".jpeg", ".png")

# Create output folders if they don't exist
for folder_name in output_folders.keys():
    os.makedirs(folder_name, exist_ok=True)

# List all image files in the current directory
image_files = [file for file in os.listdir() if file.lower().endswith(file_extensions)]

for image_file in image_files:
    img = Image.open(image_file)
    original_width, original_height = img.size

    for folder_name, settings in output_folders.items():
        print(f"Processing {image_file} at width {settings['width'] if settings['width'] else 'max'}")
        target_width = settings["width"]
        quality = settings["quality"]

        if target_width and original_width > target_width:
            # Calculate new height while maintaining aspect ratio
            target_height = int(original_height * (target_width / original_width))
            img_resized = img.resize((target_width, target_height), Image.ANTIALIAS)
        else:
            img_resized = img

        # Change the file extension to '.webp'
        output_filename = os.path.splitext(image_file)[0] + ".webp"
        output_path = os.path.join(folder_name, output_filename)
        img_resized.save(output_path, "WEBP", quality=quality)


    img.close()

print("Images have been processed and saved in respective folders.")

Footnotes

  1. These quality settings may seem excessive, but these settings were for a photography portfolio website. The 85% setting declared by others as 'high quality' is noticably lacking when it comes to photography.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment