Retrieving Image Dimensions with Python: Using PIL and Pillow

Introduction

In the realm of image processing, being able to retrieve and manipulate an image’s dimensions is a fundamental task. Python, renowned for its simplicity and readability, offers several libraries that can help you easily obtain an image’s size. Among these, the Python Imaging Library (PIL) and its actively maintained fork, Pillow, are popular choices due to their ease of use and comprehensive features.

This tutorial will guide you through retrieving the dimensions of an image using both PIL and Pillow, highlighting installation, usage, and additional considerations for handling image orientation based on EXIF data. We’ll also touch upon alternative libraries that can be used for similar tasks.

Getting Started with Pillow

Pillow is a fork of PIL, maintaining compatibility while providing support for modern Python versions (including Python 3). It offers robust functionality for opening, manipulating, and saving many different image file formats.

Installation

To install Pillow, you’ll need to have pip installed. If your system allows it, run the following command:

pip install Pillow

If you lack administrative privileges, use:

pip install --user Pillow

This will install Pillow locally for your user account.

Using Pillow to Retrieve Image Dimensions

Once Pillow is installed, retrieving an image’s dimensions is straightforward. Here’s a step-by-step guide:

  1. Import the Required Module:

    Begin by importing the Image class from the PIL package.

    from PIL import Image
    
  2. Open the Image File:

    Use the open() function to load your image file into a Pillow object. It’s advisable to use a context manager (with statement) for handling files, which ensures proper resource management.

    with Image.open('path_to_your_image.png') as img:
        width, height = img.size
        print(f'Width: {width}, Height: {height}')
    

    This will output the dimensions of your image, providing a tuple containing its width and height in pixels.

Handling EXIF Orientation

EXIF data often contains metadata such as orientation flags indicating how an image should be displayed. PIL does not automatically apply this rotation when opening images. Therefore, if you’re dealing with JPEGs (or other formats that support EXIF), you might need to adjust the dimensions accordingly:

def get_image_dims(file_path):
    from PIL import Image as pilim
    im = pilim.open(file_path)
    
    # Check for orientation flag in EXIF data
    exif_orientation_tag = 274
    if im._getexif() and exif_orientation_tag in im._getexif():
        orientation = im._getexif()[exif_orientation_tag]
        
        # Swap dimensions based on the orientation flag
        if orientation in {3, 4, 5, 6, 7, 8}:
            return (height, width)
    
    # Default to original size if no rotation is needed
    return im.size

file_path = 'path_to_your_image.jpg'
dimensions = get_image_dims(file_path)
print(f'Corrected Dimensions: {dimensions}')

This function checks the orientation flag and returns the dimensions adjusted for any rotations.

Alternative Libraries

Using Imageio

Imageio is another library that can be used to read image files, especially when scipy.ndimage.imread is deprecated. It’s simple and efficient:

  1. Installation:

    pip install imageio
    
  2. Retrieve Dimensions:

    import imageio
    
    image = imageio.imread('path_to_your_image.png')
    height, width, channels = image.shape
    print(f'Width: {width}, Height: {height}')
    

Using Pygame for Game Developers

For game developers working with Pygame, you can easily retrieve dimensions:

  1. Installation:

    pip install pygame
    
  2. Retrieve Dimensions:

    import pygame
    
    img = pygame.image.load('path_to_your_image.png')
    width = img.get_width()
    height = img.get_height()
    print(f'Width: {width}, Height: {height}')
    

Conclusion

Retrieving image dimensions is a simple task with Python, thanks to libraries like Pillow and Imageio. Whether you’re working on desktop applications or games, these tools provide powerful yet straightforward methods for handling images. Always remember to consider EXIF data when dealing with JPEGs, as it might affect the perceived orientation of your images.

This tutorial has equipped you with the knowledge to manage image dimensions effectively using Python. Continue exploring other features offered by these libraries to leverage their full potential in image processing projects.

Leave a Reply

Your email address will not be published. Required fields are marked *