This article is part of in the series
Last Updated: Wednesday 14th August 2013
The module we use in this recipe to resize an image with Python is PIL. At the time of writing, it is only available for Python 2.x. If you want to do more with image editing, be sure to checkout our article on how to watermark an image in Python

Python is a very powerful scripting language and you will be pleasantly surprised to find that a lot of the common functions you would want to build are available to
you in library form. The Python ecosystem is very alive and full of libraries.

Point in case, today I will show you how to easily build a Python script that will resize an image with Python, and we will extend it to resize all images in a folder to the dimensions you choose. This is using Python's PIL (Python Imaging Library). First we'll need to install this.

Installing PIL on Windows

You can download and install the PIL library here.

Installing PIL on Mac

With MacPorts, you can install PIL with the following command (for Python 2.7):

Installing PIL on Ubuntu

Installing PIL on Linux tends to vary per distribution, so we'll only cover Ubuntu. To install PIL on Ubuntu, use the following command:

You can also use pip, such as follows:

Okay, onto the script to resize an image!

Resizing an Image with Python

To resize one image with Python's PIL, we can use the following command:

That assumes that we already know the width and height. But what if we only know the width and need to calculate the height? When resizing an image with Python, we can calculate the height as follows:

Simple! Now we show you how to batch resize images with Python.

Batch Resize Images with Python

This is how you will invoke the script:

First let’s import what we need in order for this script to work:

  • OS: Lets us access functions that will interact with our computer, in this case, fetching files from a folder.
  • getopt: Lets us easily access command line arguments passed in by the end user.
  • Image: Will allow us to invoke the resize function that will perform the heavy lifting of the application.

Our Batch Image Resizer Command Line Arguments

Next, let's go ahead and process the command line arguments. We also have to take into account the slight chance that an argument is missing. In this case, we’ll display an error message and terminate the program.

The comments above are pretty self explanatory. We parse the arguments, set variables with defaults values for usage, and assign them. If one or more variable is missing, we terminate the application.

Great, now we can focus on the purpose of this script. Let’s fetch each image in the folder and process it.

The Image.open function is returning an Image object, which in turn lets us apply the resize method on it. We use the Image.BILINEAR algorithm, for simplicity.

And that's all there is to it. As you can see Python is quite an agile language and allows developers to focus on solving business needs.