0
0
PythonHow-ToBeginner · 3 min read

How to Get Image Size in Python: Simple Guide

You can get an image's size in Python using the Pillow library by opening the image with Image.open() and accessing its size attribute. This returns a tuple with the width and height in pixels.
📐

Syntax

Use the Pillow library's Image.open() function to load an image file. Then, access the size attribute of the image object to get its width and height.

  • Image.open(path): Opens the image file at path.
  • image.size: Returns a tuple (width, height) in pixels.
python
from PIL import Image

image = Image.open('path/to/image.jpg')
width, height = image.size
💻

Example

This example shows how to open an image file and print its width and height in pixels.

python
from PIL import Image

# Open an image file
image = Image.open('example.jpg')

# Get image size
width, height = image.size

# Print the size
print(f'Width: {width} pixels')
print(f'Height: {height} pixels')
Output
Width: 800 pixels Height: 600 pixels
⚠️

Common Pitfalls

Common mistakes when getting image size in Python:

  • Not installing the Pillow library. Install it with pip install Pillow.
  • Using the wrong file path or filename causes a FileNotFoundError.
  • Trying to get size from unsupported or corrupted image files.
  • Confusing image.size tuple order; it is always (width, height).
python
from PIL import Image

# Wrong: size order confusion
image = Image.open('example.jpg')
height, width = image.size  # This is incorrect

# Correct:
width, height = image.size
📊

Quick Reference

Summary tips for getting image size in Python:

  • Always use Image.open() from Pillow to load images.
  • Access image.size for (width, height).
  • Handle exceptions for missing files or unsupported formats.
  • Install Pillow with pip install Pillow before running code.

Key Takeaways

Use Pillow's Image.open() to load images and get size with image.size.
The size attribute returns (width, height) in pixels.
Install Pillow using pip before running image size code.
Check file paths carefully to avoid errors.
Handle unsupported or corrupted images gracefully.