How do I get the picture size with PIL?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Getting image dimensions is one of the most common tasks in image pipelines. With Pillow, the actively maintained fork of PIL, you can read width and height without loading full pixel data into memory in many formats. This is useful for validation, thumbnail workflows, and dataset quality checks.
Read Width and Height with Pillow
The fastest path is opening the file with Image.open and reading the size property. size returns a two-item tuple containing width and height in pixels.
Using a context manager ensures the file handle closes immediately, which matters when processing many files.
Validate Dimensions in Upload Pipelines
A typical web workflow checks dimensions before accepting user uploads. You can enforce min and max limits and return clear validation errors.
This pattern is easy to integrate in API handlers before persisting files.
Batch Processing and Reporting
For data teams, a single-file check is rarely enough. Batch scanning helps detect inconsistent sources before model training or media generation.
Once you have a table of dimensions, you can identify outliers and standardize resize rules.
Orientation and Metadata Considerations
A subtle detail is EXIF orientation. Some photos from phones can report one width and height pair while intended display orientation is rotated. If your downstream task depends on display orientation, normalize using ImageOps.exif_transpose before measuring.
For strict computer vision preprocessing, document whether you use raw metadata dimensions or normalized display dimensions so every stage is consistent.
Performance Notes
Reading metadata is much cheaper than decoding full arrays, but it still does file I/O. If you have massive datasets, avoid reopening the same file repeatedly in separate pipeline steps. Cache results or produce a single manifest file that all jobs consume.
Also keep error handling explicit. Corrupt files, truncated downloads, and renamed non-image files happen often in real-world datasets. Robust scanning code should skip invalid inputs while recording enough context for cleanup.
Common Pitfalls
The most common mistake is forgetting to close image files, which can exhaust file descriptors in large scans. Another issue is assuming every path with an image extension is valid image content. You should catch UnidentifiedImageError and continue. Teams also overlook EXIF orientation and end up with inconsistent width and height logic between upload validation and UI rendering. Finally, avoid reading image size after converting to another format unless conversion is intentional, since dimensions can change during preprocessing steps such as crop or resize.
Summary
- Use
Image.openand.sizefor a direct width-height lookup. - Always open images with a context manager for safe file handling.
- Add dimension validation rules for upload pipelines.
- Batch scan directories to detect outliers and corrupt files early.
- Decide clearly between raw metadata size and EXIF-normalized display size.
Related reading
- How do I install opencv using pip?
- How do I install Python OpenCV through Conda?
- How do I pass an OpenCV Mat into a C Tensorflow graph?
- How do I read image data from a URL in Python?
- How do I get the row count of a Pandas DataFrame?
- How do I get time of a Python program's execution?
- How do I resize the UIImage to reduce upload image size
- How do I sample a line across a blob at a perpendicular angle? in Python/OpenCV unless you suggest switching to something else
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.