How to Bulk Resize Photos IN PYTHON

Optimising images for your digital products is becoming more and more important to keep your websites or apps’ load time as fast as possible. In fact, one of the most common reasons for performing badly on Google’s SEO (Search Engine Optimisation) is slow image load time. 

The best way to optimise your images is to ensure they are the right size for your application, e.g. mobile vs desktop website. Also, it is super tedious to manually export images to different image sizes.

I wrote a Python script to bulk resize all the images within a directory. Let’s see how.

1. Get the PIL library

We will start by installing the ‘pillow’ library. 

Pillow is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is a great tool that we will use to resize our images.

python3 -m pip install Pillow

2. Build the script

In this example, we will convert a directory with png images. PIL supports all major image formats and you can alter your file type by editing the variable ‘fileType’ below.

Next, we will add the scale of the resulting image we want in the variable ‘scale’. 

#!/usr/bin/env python3

from PIL import Image
import os, sys

# Variables
path = os.getcwd()
dirs = os.listdir(path)
fileType = 'png'      # Define the image file type
scale = (200,200)     # Change the scale here

Next define a function to loop through all our images and then use PIL to resize. The first thing to check is that we only convert the correct fileType. In our case, if the code sees anything other than a ‘png’ file we want the code to ignore that file.

The code then resizes the image using ‘im.resize(scale, Image.ANTIALIAS)’. Note that the second parameter that uses Image.ANTIALIAS is the resampling filter. I have included some different options as well below. We can then save the image with the new scale, which overwrites the original image. Please keep the original images in a separate directory!

Note that if you save the file as a JPEG, you can add an image quality score as well e.g.  ‘imResize.save(f + ‘ resized.jpg’, ‘JPEG’, quality=90)’.

def resize():
    """
    Loop through all images of 'file type' in the current directory and resize
    input:  image.png (400 x 400)
    output: image.png (200 x 200)
    """
    for item in dirs:
        # Make sure only open the image fileType is used
        if os.path.splitext(item)[1].lower() != "."+fileType:
             continue
        # Resize the image
        if os.path.isfile(os.path.join(path,item)):
            im = Image.open(os.path.join(path,item))
            f, e = os.path.splitext(os.path.join(path,item))
            print(f'I am resizing file: {item}')
            imResize = im.resize(scale, Image.ANTIALIAS)
            imResize.save(f+"."+fileType, fileType)

Some of different resampling filters you can play around with are HERE.

Lastly, we call the function resize() and we are done.

def main():
    resize()

if __name__ == "__main__":
    main()
 

3. full code

Below is the full code to batch resize all your images! Enjoy.

#!/usr/bin/env python3

from PIL import Image
import os, sys

# Variables
path = os.getcwd()
dirs = os.listdir(path)
fileType = 'png'    # Define the image file type
scale = 200,200     # Change the scale here



def resize():
    """
    Loop through all images of 'file type' in the current directory and resize
    input:  image.png (400 x 400)
    output: image.png (200 x 200)
    """
    for item in dirs:
        # Make sure only open the image fileType is used
        if os.path.splitext(item)[1].lower() != "."+fileType:
             continue
        # Resize the image
        if os.path.isfile(os.path.join(path,item)):
            im = Image.open(os.path.join(path,item))
            f, e = os.path.splitext(os.path.join(path,item))
            print(f'I am resizing file: {item}')
            imResize = im.resize(scale, Image.ANTIALIAS)
            imResize.save(f+"."+fileType, fileType)

def main():
    resize()

if __name__ == "__main__":
    main()

Leave a Comment

Your email address will not be published. Required fields are marked *