Last modified: Apr 12, 2025 By Alexander Williams

Python Image Dimensions Guide

Working with image dimensions is a common task in Python. This guide covers how to get and change image sizes using popular libraries.

Why Image Dimensions Matter

Image dimensions define width and height in pixels. They affect file size, quality, and display. Proper handling ensures optimal performance.

In Python, you can work with dimensions using several libraries. The most common are PIL (Pillow) and OpenCV.

Getting Dimensions with Pillow

Pillow is a popular Python imaging library. Use Image.open() to load an image. Then access its size attribute.


from PIL import Image

# Open image
img = Image.open("example.jpg")

# Get dimensions
width, height = img.size
print(f"Width: {width}, Height: {height}")


Width: 800, Height: 600

This method works for JPEG, PNG, and other common formats. For more on Pillow, see our Python Image Libraries Guide.

Getting Dimensions with OpenCV

OpenCV is another powerful library for image processing. Use cv2.imread() to load images. The dimensions are in shape.


import cv2

# Read image
img = cv2.imread("example.jpg")

# Get dimensions
height, width, channels = img.shape
print(f"Width: {width}, Height: {height}")


Width: 800, Height: 600

Note: OpenCV returns height first, then width. The third value is color channels (3 for RGB).

Changing Image Dimensions

You can resize images using Pillow's resize() method. Specify the new dimensions as a tuple.


from PIL import Image

img = Image.open("example.jpg")

# Resize to 400x300
resized_img = img.resize((400, 300))
resized_img.save("resized_example.jpg")

This creates a smaller version of the original image. For more advanced processing, check our Python Image Processing Guide.

Maintaining Aspect Ratio

When resizing, you might want to keep the original proportions. Calculate new dimensions based on one side.


from PIL import Image

img = Image.open("example.jpg")
width, height = img.size

# New width, maintain ratio
new_width = 400
ratio = new_width / width
new_height = int(height * ratio)

resized_img = img.resize((new_width, new_height))

This ensures the image doesn't look stretched or squashed. The aspect ratio remains constant.

Batch Processing Images

You can process multiple images at once. This is useful for resizing entire folders of images.


import os
from PIL import Image

input_folder = "input_images"
output_folder = "resized_images"

os.makedirs(output_folder, exist_ok=True)

for filename in os.listdir(input_folder):
    if filename.endswith((".jpg", ".png")):
        img = Image.open(f"{input_folder}/{filename}")
        img.thumbnail((800, 800))  # Max dimensions
        img.save(f"{output_folder}/{filename}")

The thumbnail() method maintains aspect ratio while resizing. It's perfect for creating uniform image sets.

Checking Dimensions Without Loading

For large images, you might want to check dimensions without full loading. Pillow can do this efficiently.


from PIL import Image

with Image.open("large_image.jpg") as img:
    width, height = img.size
    print(f"Dimensions: {width}x{height}")

This method uses minimal memory. It's great for quick checks on big files.

Common Issues

When working with dimensions, you might encounter these problems:

1. Corrupted images: Some files might not load properly. Always check if the image opened successfully.

2. Wrong aspect ratio: Forced resizing can distort images. Always calculate proportional sizes when needed.

3. Memory errors: Very large images might crash your program. Consider processing in chunks.

For more on handling images, see our Python Open Digital Images Guide.

Conclusion

Python makes image dimension handling easy. Whether using Pillow or OpenCV, you can read and modify sizes with few lines of code.

Remember to maintain aspect ratios when resizing. Batch processing helps when working with multiple files.

For advanced techniques, explore our other guides on image processing and related topics.