Python Pillow - Image.size - Get Image Size


Python Pillow - Image Size

To get the size of image using Python Pillow, use size property of Image object. The size property returns the width and height of the image.

In this tutorial, we shall learn how to get the size of an image, in other words, width and height of an image, using Pillow library.

Syntax - Image size property

The syntax to use size property of PIL Image object, say image, is given below.

image.size

Examples

In the following examples, we shall see how to get the size of an image using Image.size property.

1. Get size of an image using Pillow

In this example we are given an image at path input_image.jpg. We have to get the size of this image.

First open the image using Image.open() function. The open() function returns an Image object. Then read the size property of the Image object. The size property returns a tuple of width and height. Use it as per your requirement.

Python Program

from PIL import Image

# Open the image file
image = Image.open('input_image.jpg')

# Get image_size
image_size = image.size

# Print image size
print(image_size)

input_image.jpg

Python Pillow - Image Size

Output

(480, 320)

2. Access width and height from image size using Pillow

We have seen in the previous example that size property of Image object returns a tuple of width and height.

You can access the height and width separately from size property using index notation, just like how you access individual items in a tuple.

Since width is the first element, you can use the index of 0 to access the width from the size. Similarly, you can use index of 1 to access the height from the size.

In the following program, we shall get the width and height of the image, and print them to standard output. We shall use the same input_image.jpg that we used in the previous program.

Python Program

from PIL import Image

# Open the image file
image = Image.open('input_image.jpg')

# Get image_size
image_size = image.size

# Get width and height
image_width = image_size[0]
image_height = image_size[1]

# Print width and height
print(f"Width : {image_width}")
print(f"Height : {image_height}")

Output

Width : 480
Height : 320

Summary

In this tutorial of Python Examples, we learned how to get the size of an image using Python Pillow library, and also to access width and heigh separately from the size property, with the help of well detailed example programs.