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

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.

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!

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 Soft Skills for Programmers: Why They Matter and How to Develop Them

Soft Skills for Programmers: Why They Matter and How to Develop Them

Overview You need a variety of soft skills in addition to technical skills to succeed in the technology sector. Soft skills are used by software professionals to collaborate with their peers effectively and profitably. Finding out more about soft skills and how they are used in the workplace will help you get ready for the job if you are interested in a…

James Phoenix
James Phoenix
Cover Image for What Are Webhooks? And How Do They Relate to Data Engineering?

What Are Webhooks? And How Do They Relate to Data Engineering?

Webhooks are a simple and powerful method for receiving real-time notifications when certain events occur. They enable a whole host of automated and interconnected applications. Broadly speaking, your apps can communicate via two main ways: polling and webhooks.  Polling is like going to a shop and asking for pizza – you have to ask whenever you want it. Webhooks are almost the…

James Phoenix
James Phoenix