In our previous article, Displaying and Converting Images with Python, we demonstrated how to open and show images in Python as well as how to convert them to different file formats. We also learned how to inspect basic attributes of an image. In this article, you’ll learn a few more extremely simple tricks you can do with images thanks to the power of Python.
Scaling an Image Using Python
The first manipulation you’ll see is scaling an image in Python. To scale an image, you can call the resize() method from the Image class. You simply need to pass to the method the new width and height as a tuple and it will return a new image of the new size:
NewImage = Image.scale( newWidth, newHeight)
This is best illustrated in a simple listing. Listing 1 takes an image and reduces its size in 200 by 200 pixels.
Listing 1: Resizing an image in Python
from PIL import Image import os if os.path.exists("newImage.jpg"): os.remove("newImage.jpg") img = Image.open('mars.jpg') newImage = img.resize((200,200)) newImage.save("newImage.jpg")
Like the listings in the previous article, this listing is very straightforward. We start by importing the Python Image and os modules. We need the Image module for the image manipulation. We need the os module for the next two lines of code in Listing 1, which check to see if an image file named “newImage.jpg” already exists in the current directory. If it does, then we use the os.remove() method to delete it.
The code then opens an image called mars.jpg. This is a 640×640 image of Mars, which is shown below. We then call the resize() method on this image to change the size to 200 by 200. This much smaller image is then assigned to the newImage variable. Finally, we save our new image. Once done, we have another image that is 200×200. The newly sized image is shown under the original image here:
In Listing 1, the dimensions of the image were kept consistent. It is possible to resize the width separate from the height. The following shows the same listing, but this time the resizing tuple set to (600, 100).
Because the width and height can be scaled separately, you should use caution when scaling to keep the proportions in sync.
The resize method can also be used with additional parameters. One that is handy is a box value. The box value is a tuple that contains four numbers. These numbers are a region within the image that you want to resize. The format uses two x,y coordinates, one for a starting position and the other for the ending position. The upper left corner of the image would be 0, 0 going up to the size of the image where the lower right corner is (width, height). By default, the box value is (0, 0, width, height) for the image.
Using the Mars image, if you wanted to crop a portion out of the image and resize it to the size of the original image, you would add the box parameter as shown in Listing 2.
Listing 2: Boxing and resizing in Python
from PIL import Image import os if os.path.exists("newImage.jpg"): os.remove("newImage.jpg") img = Image.open('mars.jpg') newImage = img.resize((img.width, img.height), box=(199, 199, 439, 439)) newImage.save("newImage.jpg")
When you run this listing, the Mars.jpg image will be again saved as a file called newImage.jpg. This time the image will be a portion out of the middle of the original image that is resized as shown here:
Creating a Thumbnail Using Python
Similar to resizing an image, sometimes you simply want to create a thumbnail. The Python image class includes a method specifically for creating thumbnails. This method takes the current image file and converts it to a thumbnail that is sized based on a (width, height) tuple you pass to it:
img.thumbnail((50,50))
You should note that the thumbnail() method replaces the information stored in the existing image file. If this is an issue, you’ll want to copy the image prior to calling thumbnail(). In Listing 3, a thumbnail is created and saved using a new filename to avoid overwriting the original file.
Listing 3: Creating a thumbnail
from PIL import Image img = Image.open('mars.jpg') newImage = img.thumbnail((50,50)) img.save('mars_thumbnail.jpg')
Rotating an Image Using Python
Another method of the image class is rotate(). This method allows you to rotate an image based on an angle measured in degrees and going in a counterclockwise direction. Listing 4 presents the code to rotate an image 45 degrees.
Listing 4: Basic rotation of an image in Python
from PIL import Image import os if os.path.exists("newImage.jpg"): os.remove("newImage.jpg") img = Image.open('beach.jpg') newImage = img.rotate(45) newImage.save('newImage.jpg')
The result of running this listing is that an image is rotated. The following shows the original image and the version rotated 45 degrees:
There are several optional parameters you can use with rotate as well. The two that are most likely to be useful are center and fillcolor. The center parameter lets you pick the point that the image should rotate around. By default, the image will rotate around the center as shown in the image produced by Listing 4. You can, however, change the center by setting a tuple value for the coordinates to spin around. The upper left corner would be (0,0) and the bottom right would be (width, height).
You can also set the fill color. This is the color of the area that is shown without an image after the rotation. In the image above this is black. You can set the new color using a tuple with RBB values. For example, to set a color to pink, you’d use (255, 200, 200). For bright red, you could use (255, 0, 0). Listing 5 shows the code to rotate the beach image around a point nearer the top left corner (30,30), and it uses a pink fill color:
Listing 5: Rotating in Python Around a Point
from PIL import Image import os if os.path.exists("newImage.jpg"): os.remove("newImage.jpg") img = Image.open('beach.jpg') newImage = img.rotate(45, center=(30,30),fillcolor=(255, 200, 200)) newImage.save('newImage.jpg')
The output of this listing is:
Wrapping Up
This article moved a little deeper into manipulating images with Python. Once again, with just a few lines of Python code you’ve seen how to resize, crop, and rotate images.