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 atpath.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
Pillowlibrary. Install it withpip install Pillow. - Using the wrong file path or filename causes a
FileNotFoundError. - Trying to get size from unsupported or corrupted image files.
- Confusing
image.sizetuple 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()fromPillowto load images. - Access
image.sizefor (width, height). - Handle exceptions for missing files or unsupported formats.
- Install Pillow with
pip install Pillowbefore 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.