How to Resize a Photo with Python
Sometimes you will find yourself wanting to resize a photo. I usually do this for photos I plan to email or post on a website, since some of my images can be quite large. Normal people use an image editor. I usually do as well, but for fun, I thought I would look into how to do it in Python.
The quickest way to do this is to use the Pillow package, which you can install with pip. Once you have it, open up your favorite code editor and try the following code:
Here we import the Image class from the Pillow package. Next, we have a function that takes 3 arguments: the location of the file we want to open, the location where we want to save the resized image, and a tuple representing the new image size, where the tuple contains the width and height, respectively. Next, we open our image and print out its size. Then we call the image object’s resize() method with the size tuple we passed in. Finally, we grab the new size, print it out, show the image, and then save the resized photo.
Here is what it looks like now:
As you can see, the resize() method doesn’t do any kind of scaling. We will look t how to do that next!
Scaling an Image
Most of the time, you won’t want to resize your image like we did in the previous example unless you want to write a scaling method. The problem with the previous method is that it does not maintain the photo’s aspect ratio when resizing. So instead of resizing, you can just use the thumbnail() method. Let’s take a look:
Here, we allow the programmer to pass the input and output paths, as well as our maximum width and height. We then use a conditional to determine our max size, and call the thumbnail() method on our open image object. We also pass in the Image.ANTIALIAS flag, which will apply a high-quality downsampling filter, resulting in a better image. Finally, we open the newly saved scaled image and print out its dimensions to compare with the original. If you open the scaled image, you will see that the photo's aspect ratio was maintained.
Wrapping Up
Playing around with the Pillow package is a lot of fun! In this article, you learned how to resize an image and how to scale a photo while maintaining its aspect ratio. You can now use this knowledge to create a function that iterates over a folder and creates thumbnails of all the photos in it, or you might create a simple photo-viewing application where this capability would be handy.




