How to Get the Size of an Image with PIL in Python

Problem Formulation

Given an image, how to get the size of the image with PIL or any other Python library?

Getting the size of an image with Python PIL(Python Image Library) basically implies that you want to get its height and width in pixels.

Example: Consider the following image:

🔥Challenge: Get the size of the above image with PIL or any other Python library.

Method 1: Using img.size

Approach: To get the size of the image:
➢ open it up by calling the PIL function Image.open('image file path').
➢ Then use the PIL property image.size on the opened image. This returns a tuple containing the width and height of the image in pixels.
➢ Unpack the tuple in two different variables to store the width and height individually.

code:

from PIL import Image
img = Image.open("image.jpg")
width, height = img.size
print(f'width: {width}\nheight: {height}')

Output:

width: 640
height: 426

#Alternative Formulation

Instead of using the img.size property, you can use the img.width and img.height properties to store/display the height and width of the image separately.

Here’s the code that demonstrates how you can use the width and height properties of the PIL library.

from PIL import Image
img = Image.open("image.jpg")
width = img.width
height = img.height
print(f'width: {width}\nheight: {height}')

Output:

width: 640
height: 426

🗨️TRIVIA: PIL(Python Imaging Library) is a Python library that is used for image processing. It supports numerous image formats which include “jpeg”, “png”, “ppm”, “tiff”, “bmp”, “gif”, etc. It is an extremely useful library that provides a plethora of image editing capabilities like getting the size of an image, cropping an image, etc. The Image module of the PIL library is used to represent the PIL images. 

  • To install the PIL, execute the following command in your terminal: pip install pillow

Method 2: Get Image Size Using Open-CV

Approach: To get the size of an image using OpenCV:
➢ Load the image from the specified path by calling OpenCV function imread('file_path').
➢ Use the .shape property on this image. This returns a tuple consisting of the height, width in pixels, and the number of channels of the image.
➢ Unpack these values individually in three different variables and display the output accordingly.

Code:

import cv2
image = cv2.imread('image.jpg')
height, width, channel = image.shape
print(f"width:{width}\nheight:{height}")

Output:

width: 640
height: 426

✏️Note: Use the following command to install OpenCV: pip install opencv-python

Method 3: Get the Image Size Using Pygame

  • Approach:
    • Load the image from its path using the pygame function pygame.image.load('filepath').
    • Use the methods img.get_width() and img.get_height() to get the image width and height in pixels.

Code:

import pygame
img = pygame.image.load('image.jpg')
width = img.get_width()
height = img.get_height()
print("width: ", width)
print("height: ", height)

Output:

pygame 2.1.2 (SDL 2.0.18, Python 3.9.10)
Hello from the pygame community. https://www.pygame.org/contribute.html
width: 640
height: 426

🗨️TRIVIA: pygame is a Python wrapper for the SDL library (Simple DirectMedia Layer). SDL allows cross-platform access to the system’s underlying multimedia hardware components, such as video, sound, keyboard, mouse, and joystick. Since both SDL and pygame facilitate us with a cross-platform nature, we can write game programs and create rich multimedia Python programs for almost every platform that is supported by them.

To install pygame, use the following pip command on your terminal: pip install pygame

▣ How to Get Image Size in Bytes?

Previously, we found out the size of the image, that is, the image dimensions (width and height). However, you may also need to find out the file size in bytes to decide how to use the image file. Hence, let us dive into the methods that will help us to find the image size in bytes.

Using os.stat

Approach: Call the os.stat() method on the image file and then use the st_size property upon this image to get its size in bytes.

Code:

import os
print(os.stat('image.jpg').st_size)

# 48297

◩ Using os.path.getsize

Approach: os.path.getsize() is a method of the os module that is used to get the size of a specified path. Pass the image path to this function to get the size of the image file in bytes.

Code:

import os
print(os.path.getsize('image.jpg'))

# 48297

◩ Using PIL

Approach: Call the PIL function Image.open() to open the image and then use the len() method to find its length after reading the image.

Code:

from PIL import Image
img = Image.open('image.jpg')
print("File Size In Bytes:- "+str(len(img.fp.read())))

🎁Bonus: Get the Size of an Image by Loading Image from an URL

The following code demonstrates how you can load an image from an URL and then get its size.

Code:

import requests
from PIL import Image
from io import BytesIO
header = {'User-Agent': 'Mozilla/5.0 (X11; CrOS x86_64 14588.98.0) AppleWebKit/537.36 (KHTML, like Gecko) '
                   'Chrome/101.0.4951.59 Safari/537.36'}
res = requests.get("https://blog.finxter.com/wp-content/uploads/2022/05/sample_img.png", headers=header)
# create image from binary content
img = Image.open(BytesIO(res.content))
width, height = img.size
print(f'width:{width}, height:{height}')

Output:

width:867, height:489

Conclusion

We successfully unearthed the answer to numerous questions, including how to use different libraries to find the image size – dimensions as well as the size in bytes. I hope this tutorial helped you. Please subscribe and stay tuned for more interesting tutorials.

Happy learning!😊


  • One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
  • So, do you want to master the art of web scraping using Python’s BeautifulSoup?
  • If the answer is yes – this course will take you from beginner to expert in Web Scraping.