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.

image compression in python

Comparing both images:

compressing both images

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)
compressing multiple images using python

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 = '/Users/jamesaphoenix/Desktop/Imran_And_James/Python_For_SEO/7_image_compression/subdirectory/'
print(subdirectory_path)
compress_images(directory=subdirectory_path)
compressing images in a subdirectory

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!