How do I get the picture size with PIL?


How do I get a size of a pictures sides with PIL or any other Python library?

1/5/2016 9:08:17 AM

Accepted Answer

from PIL import Image

im ='whatever.png')
width, height = im.size

According to the documentation.

1/4/2018 12:29:49 PM

You can use Pillow (Website, Documentation, GitHub, PyPI). Pillow has the same interface as PIL, but works with Python 3.


$ pip install Pillow

If you don't have administrator rights (sudo on Debian), you can use

$ pip install --user Pillow

Other notes regarding the installation are here.


from PIL import Image
with as img:
    width, height = img.size


This needed 3.21 seconds for 30336 images (JPGs from 31x21 to 424x428, training data from National Data Science Bowl on Kaggle)

This is probably the most important reason to use Pillow instead of something self-written. And you should use Pillow instead of PIL (python-imaging), because it works with Python 3.

Alternative #1: Numpy

import scipy.ndimage
height, width, channels = scipy.ndimage.imread(filepath).shape

Alternative #2: Pygame

import pygame
img = pygame.image.load(filepath)
width = img.get_width()
height = img.get_height()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow