Python program to find the size (resolution) of an image

Size (resolution) of an image using Python: In this tutorial, we will learn how to find the size (resolution) of an image in Python using multiple approaches. By IncludeHelp Last updated : August 13, 2023

JPEG is a compression technique for image compression which stands for Joint Photographic Experts Group. JPEG file format (even other file formats) have a fixed header called Header format that contains useful information about that format. By using this information and Python libraries, we can find the size (resolution) of an image.

Using the Python Imaging Library (PIL)

To find the size (resolution) of an image by using the Python Imaging Library (PIL), you can use the open() method and the size property that returns the width and height of the image.

Example

In this example, we are finding the size (resolution) of an image using the Python Imaging Library (PIL).

from PIL import Image

# Function to find the size (resolution) of an image
def getImageResolution(path):
    try:
        imageObj = Image.open(path)
        imgWidth, imgHeight = imageObj.size
        return imgWidth, imgHeight
    except Exception as e:
        return None

# Mian code
if __name__ == "__main__":
    imagePath = "image1.jpg" # Path to the image
    imageResolution = getImageResolution(imagePath)
    
    if imageResolution:
        width, height = imageResolution
        print(f"Image resolution is: {width}x{height}")
    else:
        print("Unable to get image resolution.")

Using the JPEG Header Format

By extracting the data from the JPEG image header format, you can find the size (resolution) of an image. To get the height and width you need to extract the two-two bytes from the 164th position from the Header format.

Example

In this example, we are reading the JPEG file's header format and then extracting the height and width of the image from it.

# Function to find the size (resolution) of an image
def getImageResolution(path):
    # open image in read mode
    with open(path, "rb") as imageObj:

        # set the file pointer at 163th index
        # to get the height and width which are from 164th position
        # Note: Index starts from 0
        imageObj.seek(163)

        # read the 2 bytes to get the height value
        extData = imageObj.read(2)

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

        # next 2 bytes to get the width value
        data = imageObj.read(2)

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

        print(f"Image resolution is: {width}x{height}")

# Call the function
getImageResolution("image1.jpg")

Resources

Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.