Python Tutorials

Python Programs

Python Find the Size of an Image


Python Find the Size of an Image

In this tutorial, we will learn how to find the size of an image in Python. We will cover the basic concept of image processing and use the PIL (Pillow) library to get the dimensions of an image.


What is Image Processing

Image processing involves performing operations on images to extract useful information or to modify the image in some way. Finding the size of an image is a common task in image processing.


Syntax

The syntax to find the size of an image in Python using the Pillow library is:

from PIL import Image

def find_image_size(image_path):
    with Image.open(image_path) as img:
        return img.size


Finding the size of an image

We can create a function to find the size of an image by opening the image file and getting its dimensions using the Pillow library.

For example,

  1. Import the Image class from the PIL library.
  2. Define a function named find_image_size that takes one parameter image_path.
  3. Use the Image.open method to open the image file.
  4. Get the size of the image using the size attribute of the image object.
  5. Return the dimensions of the image as a tuple.
  6. Call the function with a sample image file path and print the result.

Python Program

from PIL import Image

def find_image_size(image_path):
    with Image.open(image_path) as img:
        return img.size

# Sample image file path
image_path = 'sample_image.jpg'

# Find the size of the image
result = find_image_size(image_path)

# Print the result
print('Size of the image is:', result)

Output

Size of the image is: (width, height)