How to Resize All Images in a Folder using Python

image resize python

Resizing images is a common task in the digital world, often necessary for optimizing website performance or simply making files easier to handle. While there are numerous tools available for this purpose, Python, a versatile and efficient programming language, offers a powerful solution.

This short article will provide a comprehensive guide on how to resize all images in a folder using Python. We will specifically focus on using the Python Imaging Library (PIL), also known as Pillow, to accomplish this task.

Why Image Resizing is Important

Image resizing is a seemingly simple yet crucial step in many modern digital workflows, ubiquitous in web development to machine learning fields. Larger, high-resolution images consume a lot of memory, putting strain on storage and slower loading times on websites or mobile apps.

By resizing images, you can optimize their size, reduce bandwidth consumption, and improve the overall performance and user experience. As an added benefit, it can also help to standardize your dataset in projects that involve image processing.

Interestingly, image resizing isn’t just about making images smaller. Sometimes, you’ll want to enlarge images for visibility or specific requirements. However, direct scaling can lead to pixelation and blurring. Proper image resizing allows for interpolation, resulting in a clearer and sharper enlarged image quality.

In machine learning and AI, resizing images to a uniform dimension is often necessary before feeding them into a model. With Python, these tasks are pretty straightforward. In fact, with just a few lines of code, you can resize a whole batch of images stored in a folder on your system.

Let’s get started with the steps to resize all images in a folder using Python.

Step 1: Setting Up Our Project

First, we need to install the Pillow library. If you haven’t installed it yet, you can use pip, Python’s package installer. Let’s open our command prompt and type the following command:

pip install pillow

After installing Pillow, we need to import it into our Python script. We also need the OS module to interact with the operating system. Our import statements should look like this:

from PIL import Image
import os

After that, we’ll need to specify the path where your images are stored.

path = '/your/images/folder'

Remember to replace this with the actual path where your images are located on your system.

Step 2: Define the Function to Resize Images

Next, we define a function that takes width and height as parameters. This function will loop through all the images in the folder.

def resize(width, height):
	for item in dirs:
		if os.path.isfile(path + item):
			img = Image.open(path + item)
			new_image = img.resize((width, height))
			new_file_name = 'resized-' + item
			new_image.save(path + new_file_name)

Finally, we run the function with the desired width and height.

resize(500, 500)

As a note, all your new images will be saved in the folder with the prefix “resized” from this method. This is because we append the filename with “resized” to differentiate them from the original image.

Resizing Images at Scale With Cloudinary

While Python and the PIL library provide an easy solution for resizing all images in a folder, doing this task repeatedly with different folders, images, and dimensions can be time-consuming. Additionally, managing and storing these resized images can become an issue, especially when dealing with large quantities.

This is where Cloudinary, a cloud-based image and video management service, comes in as a game-changer. Not only does it offer a generous free-forever subscription plan, but it also provides a range of built-in effects, filters, and modifications.

Resizing an image can be easily done on the fly in the cloud, where you can easily specify the width, height, and aspect ratio for your images. Cloudinary will automatically resize and crop them to meet your criteria.  You can save a significant amount of time and effort, allowing you to scale your image management tasks efficiently.

Optimize, transform, and manage your media assets like a pro with Cloudinary. Sign up for free today!

QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you better resize all images in a folder using Python:

  1. Batch process large folders with multithreading
    When resizing a large number of images, use Python’s concurrent.futures module to apply multithreading. This will process multiple images in parallel, reducing overall execution time for batch operations significantly.
  2. Maintain aspect ratio to avoid distortion
    Instead of hardcoding width and height, resize images proportionally by keeping the aspect ratio. You can calculate the new dimensions by setting only the width or height and adjusting the other dimension to maintain the ratio using img.thumbnail() from PIL.
  3. Compress images without sacrificing quality
    After resizing, compress images to reduce file sizes further by using PIL’s save() function with the optimize=True and quality=85 parameters. This allows you to retain high-quality visuals while reducing file size.
  4. Check for file types and handle errors
    Ensure that only valid image files are processed by checking the file extension before attempting to open them. You can use the imghdr module to verify file types and implement exception handling to skip corrupt or unsupported files.
  5. Resize based on the longest edge for consistency
    When dealing with images of varying orientations (landscape vs. portrait), resize them based on the longest edge to maintain visual consistency across the batch. This ensures that all images maintain proportional scaling regardless of their initial orientation.
  6. Use EXIF data to correct orientation
    Images captured on mobile devices often contain EXIF metadata that specifies their orientation. Use the ImageOps.exif_transpose() function in Pillow to automatically rotate images based on this data before resizing, preventing improperly oriented outputs.
  7. Save images in multiple formats
    If you need to support multiple formats (e.g., JPEG, PNG, WebP), modify the save function to output resized images in multiple formats. This can be achieved by simply adding a loop to save each image in the desired formats, making your code more versatile.
  8. Set up automatic backups of original images
    Before resizing, create backups of the original images by copying them to a backup folder. This ensures that your original files are preserved and available if you need to revert any changes or reprocess images with different dimensions.
  9. Process images recursively in nested folders
    If your images are stored in subdirectories, use os.walk() instead of os.listdir() to traverse through all the nested folders and resize images recursively. This makes your script more adaptable to complex folder structures.
  10. Create a command-line interface (CLI) for flexibility
    Add flexibility by turning your script into a CLI using the argparse module. This allows users to specify the input folder, output folder, target dimensions, and image format as command-line arguments, enabling easier integration into different workflows.

These advanced tips will help you handle image resizing in Python more efficiently, improving both performance and flexibility in your projects.

Last updated: Oct 1, 2024