"
This article is part of in the series
Published: Wednesday 7th March 2012
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):

[shell]
$ port install py27-pil
[/shell]

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:

[shell]
$ sudo apt-get install libjpeg libjpeg-dev libfreetype6 libfreetype6-dev zlib1g-dev
[/shell]

You can also use pip, such as follows:

[shell]
$ pip install PIL
[/shell]

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:

[python]
from PIL import Image

width = 500
height = 500

# Open the image file.
img = Image.open(os.path.join(directory, image))

# Resize it.
img = img.resize((width, height), Image.BILINEAR)

# Save it back to disk.
img.save(os.path.join(directory, 'resized-' + image))
[/python]

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:

[python]
from PIL import Image

baseWidth = 500

# Open the image file.
img = Image.open(os.path.join(directory, image))

# Calculate the height using the same aspect ratio
widthPercent = (basewidth / float(img.size[0]))
height = int((float(img.size[1]) * float(widthPercent)))

# Resize it.
img = img.resize((baseWidth, height), Image.BILINEAR)

# Save it back to disk.
img.save(os.path.join(directory, 'resized-' + image))
[/python]

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:

[shell]
python image_resizer.py -d 'PATHHERE' -w 448 -h 200
[/shell]

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

[python]
import os
import getopt
import sys
from PIL import Image
[/python]

  • 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.

[python]
# Let's parse the arguments.
opts, args = getopt.getopt(sys.argv[1:], 'd:w:h:')

# Set some default values to the needed variables.
directory = ''
width = -1
height = -1

# If an argument was passed in, assign it to the correct variable.
for opt, arg in opts:
if opt == '-d':
directory = arg
elif opt == '-w':
width = int(arg)
elif opt == '-h':
height = int(arg)

# We have to make sure that all of the arguments were passed.
if width == -1 or height == -1 or directory == '':
print('Invalid command line arguments. -d [directory] ' \
'-w [width] -h [height] are required')

# If an argument is missing exit the application.
exit()
[/python]

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.

[python]
# Iterate through every image given in the directory argument and resize it.
for image in os.listdir(directory):
print('Resizing image ' + image)

# Open the image file.
img = Image.open(os.path.join(directory, image))

# Resize it.
img = img.resize((width, height), Image.BILINEAR)

# Save it back to disk.
img.save(os.path.join(directory, 'resized-' + image))

print('Batch processing complete.')
[/python]

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.