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):
$ port install py27-pil
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:
$ sudo apt-get install libjpeg libjpeg-dev libfreetype6 libfreetype6-dev zlib1g-dev
You can also use
pip, such as follows:
$ pip install PIL
Okay, onto the script to resize an image!
- Watermark your Images in Python 2.x
- Install PySide and PyQt on Windows, Mac and Linux
- How to Use the Twython (Twitter) Python library
Resizing an Image with Python
To resize one image with Python’s PIL, we can use the following command:
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))
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:
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)) height = int((float(img.size) * float(widthPercent))) # Resize it. img = img.resize((baseWidth, height), Image.BILINEAR) # Save it back to disk. img.save(os.path.join(directory, 'resized-' + image))
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:
python image_resizer.py -d 'PATHHERE' -w 448 -h 200
First let’s import what we need in order for this script to work:
import os import getopt import sys from PIL import Image
- 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
resizefunction 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.
# 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()
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.
# 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.')
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.