Python Program to Find the Size and Dimension of an Image

In this example, we will write a python program to find the size and dimension of an image. To better understand this example, make sure you have knowledge of the following tutorials:-

Here is the code to find size and dimension of an image named “sample_image_file.jpg”, the sample is as provided.

import os


def getSize(filename):
    st = os.stat(filename)
    return st.st_size


def getDimension(filename):
   # open image for reading in binary mode
   with open(filename,'rb') as img_file:

       # height of image (in 2 bytes) is at 164th position
       img_file.seek(163)

       # read the 2 bytes
       a = img_file.read(2)

       # calculate height
       height = (a[0] << 8) + a[1]

       # next 2 bytes is width
       a = img_file.read(2)

       # calculate width
       width = (a[0] << 8) + a[1]

       print("The dimension of the image is",width,"x",height)

filePath = "sample_image_file.jpg"
print("The size of file is " + str(getSize(filePath)) + " bytes")
getDimension(filePath)

The output of the program is:-

The size of file is 66027 bytes
The dimension of the image is 768 x 512

Python Program to Find Dimension of an Image using PIL module

For this, you need to install PIL using pip install PIL.

from PIL import Image

filePath = "sample_image_file.jpg"
img = Image.open(filePath)
width, height = img.size
print("The dimension of the image is", width, "x", height)

The output of the program is:-

The dimension of the image is 768 x 512
SHARE Python Program to Find the Size and Dimension of an Image

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share