How To Compress Multiple Images In Python

James Phoenix
James Phoenix

Learning Outcomes

  • To learn how to compress a single image.
  • To learn how to compress all images within a specific directory.

As approximately 65% of today’s online content is made of image, decreasing the time your users have to wait to view content is an essential part of your website or application.

This article will show you how to effectively compress your images using Python!


Why Should You Optimise Your Images?

There are three major reasons for optimising your images:

  • SEO: Smaller images means that your website or app will load faster, this ensures that users are able to consume either your content or service quickly. Also Google have stated that site speed is a small ranking factor for Google search.
  • Storage: Optimised images are cheaper to store, therefore reducing your operational costs.
  • Bandwidth: Optimised images require less i/o (input / output) bandwidth, which means you can get more out of your existing hosting plans, or AWS/Google Cloud Platform/Digital Ocean plans.

Image Optimisation In Python

There many libraries that allow you to easily optimise images with Python:

  • Pillow – This library builds on top of PIL and can be used for the following image formats: PNG, PPM, JPEG, GIF, BMP and TIFF.
  • img4web – This script optimises .jpg and .png images for the web, after running it you’ll receive lossless compression for the images.
  • Tinify – This package allows you to easily integrate with tinypng.com for receiving compressed images over an API.
  • Scikit-image – Scikit-learn is a machine learning package, the scikit-image package allows for advanced manipulation of images, allowing you to even return the images as numpy arrays!
  • Pyguetzli – A Python binding for Google’s Guetzli library, which is a JPEG encoder that yields 20-30% smaller images in comparison to libjpeg.

For this tutorial, we will use pillow to do our image compression with python, so let’s install it:

!python3 -m pip install --upgrade pip
!python3 -m pip install --upgrade Pillow

How To Open A Single Image In Python

The most important class in Pillow is called: Image

Unleash Your Potential with AI-Powered Prompt Engineering!

Dive into our comprehensive Udemy course and learn to craft compelling, AI-optimized prompts. Boost your skills and open up new possibilities with ChatGPT and Prompt Engineering.

Embark on Your AI Journey Now!
from PIL import Image
import PIL
import os
import glob

You can use dir(Image) to see what methods and attributes are available on the Image class:

dir(Image)

im = Image.open("image-1.jpg")
print(f"The image size dimensions are: {im.size}")
# The image size dimensions are: (1920, 1280)

How To Compress A Single Image In Python

file_name = 'image-1-compressed.jpg'
picture = Image.open('image-1.jpg')
dim = picture.size
print(f"This is the current width and height of the image: {dim}")
This is the current width and height of the image: (1920, 1280)

  • You will then need to select the specific quality of image from 0 – 100:
  • A quality of 85 doesn’t make much difference for 5 – 6mb files, and shantanujoshi found that 65 for the quality argument is the lowest reasonable number.
picture.save("Compressed_"+file_name,optimize=True,quality=30) 

However, I tried with the quality set at 30 and the two images still seemed similar in terms of image quality.


How To Compress Multiple Images In The Current Working Directory

We will use Python’s OS package to find and compress every image within the current working directory:


For this example, you can download three images from pexels and put them inside of your current working directory.

Make sure to include “example” in every images’ file name:

print(f"The current working directory: {os.getcwd()} ")
# The current working directory: /Users/jamesaphoenix/Desktop/Imran_And_James/Python_For_SEO/7_image_compression 
images = [file for file in os.listdir() if file.endswith(('jpg', 'png' )) and "example" in file]
print(f" Example images: {images}")
# Example images: ['example-image.jpg', 'example-image-3.jpg', 'example-image-2.jpg']
# How to get the image name:
for image in images:
    print(image.split('.')[0])
for image in images:
    # 1. Open the image
    img = Image.open(image)
    # 2. Compressing the image
    img.save("Compressed_and_resized_"+image,
             optimize=True,
             quality=30)

How To Compress Multiple Images In A Specific File Directory

Okay great, hopefully you can now see how easy it is to compress multiple file images using Python!

Let’s do one more example, where we will change into a specific directory, extract all of the jpg and png files.

Then we will compress every image using Pillow.

def compress_images(directory=False, quality=30):
    # 1. If there is a directory then change into it, else perform the next operations inside of the 
    # current working directory:
    if directory:
        os.chdir(directory)

    # 2. Extract all of the .png and .jpeg files:
    files = os.listdir()

    # 3. Extract all of the images:
    images = [file for file in files if file.endswith(('jpg', 'png'))]

    # 4. Loop over every image:
    for image in images:
        print(image)

        # 5. Open every image:
        img = Image.open(image)

        # 5. Compress every image and save it with a new name:
        img.save("Compressed_and_resized_with_function_"+image, optimize=True, quality=quality)

The above function will by default run in the current working directory, however if we pass an exact directory path to it as the first argument, then we will change into that directory and perform the image compression on all .png and .jpg images there!

subdirectory_path = 'subdirectory/'
print(subdirectory_path)
compress_images(directory=subdirectory_path)

In the next tutorial, you’ll learn how to resize single images, multiple images and will then combine this with image compression to further improve your image processing skills with Python!

TaggedPython For SEO


More Stories

Cover Image for Why I’m Betting on AI Agents as the Future of Work

Why I’m Betting on AI Agents as the Future of Work

I’ve been spending a lot of time with Devin lately, and I’ve got to tell you – we’re thinking about AI agents all wrong. You and I are standing at the edge of a fundamental shift in how we work with AI. These aren’t just tools anymore; they’re becoming more like background workers in our digital lives. Let me share what I’ve…

James Phoenix
James Phoenix
Cover Image for Supercharging Devin + Supabase: Fixing Docker Performance on EC2 with overlay2

Supercharging Devin + Supabase: Fixing Docker Performance on EC2 with overlay2

The Problem While setting up Devin (a coding assistant) with Supabase CLI on an EC2 instance, I encountered significant performance issues. After investigation, I discovered that Docker was using the VFS storage driver, which is known for being significantly slower than other storage drivers like overlay2. The root cause was interesting: the EC2 instance was already using overlayfs for its root filesystem,…

James Phoenix
James Phoenix