How to Resize a Photo with Python

Sometimes you will find yourself wanting to resize a photo. I usually want to do this for photos that I want 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 with the Python programming language.

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:

from PIL import Image

def resize_image(input_image_path,
                 output_image_path,
                 size):
    original_image = Image.open(input_image_path)
    width, height = original_image.size
    print('The original image size is {wide} wide x {height} '
          'high'.format(wide=width, height=height))

    resized_image = original_image.resize(size)
    width, height = resized_image.size
    print('The resized image size is {wide} wide x {height} '
          'high'.format(wide=width, height=height))
    resized_image.show()
    resized_image.save(output_image_path)

if __name__ == '__main__':
    resize_image(input_image_path='caterpillar.jpg',
                 output_image_path='caterpillar_small.jpg',
                 size=(800, 400))

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 we want to save the resized image and a tuple that represents the new size the image should be where the tuple is 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 siz, print it out and then show the image before saving 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:

from PIL import Image

def scale_image(input_image_path,
                output_image_path,
                width=None,
                height=None
                ):
    original_image = Image.open(input_image_path)
    w, h = original_image.size
    print('The original image size is {wide} wide x {height} '
          'high'.format(wide=w, height=h))

    if width and height:
        max_size = (width, height)
    elif width:
        max_size = (width, h)
    elif height:
        max_size = (w, height)
    else:
        # No width or height specified
        raise RuntimeError('Width or height required!')

    original_image.thumbnail(max_size, Image.ANTIALIAS)
    original_image.save(output_image_path)

    scaled_image = Image.open(output_image_path)
    width, height = scaled_image.size
    print('The scaled image size is {wide} wide x {height} '
          'high'.format(wide=width, height=height))


if __name__ == '__main__':
    scale_image(input_image_path='caterpillar.jpg',
                output_image_path='caterpillar_scaled.jpg',
                width=800)

Here we allow the programmer to pass in the input and output paths as well as our max width and height. We then use a conditional to determine what our max size should be and then we call the thumbnail() method on our open image object. We also pass in the Image.ANTIALIAS flag which will apply a high quality down sampling filter which results in a better image. Finally we open the newly saved scaled image and print out its size to compare with the original size. If you open up the scaled image, you will see that the aspect ratio of the photo 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 could iterate over a folder and create thumbnails of all the photos in that folder or you might create a simple photo viewing application where this sort of capability might be handy to have.


Related Reading