How to Find the Size of an Image in Python

In this tutorial, we’ll learn how to program "How to Find the Size of an Image in Python." We’ll focus on retrieving the actual resolution of an image. The objective is to accurately obtain the image's dimensions. I'll provide a sample program to demonstrate the coding process, making it easy to understand and implement. So, let’s get started!

This topic is straightforward to understand. Just follow the instructions I provide, and you'll be able to complete it with ease. The program I'll show you demonstrates the proper way to retrieve the full resolution of an image. I'll also provide a simple and efficient method to achieve this effectively. So, let’s start coding!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def jpeg_size(filename):
  2.  
  3.    with open(filename,'rb') as img_file:
  4.  
  5.      
  6.        img_file.seek(163)
  7.  
  8.  
  9.        a = img_file.read(2)
  10.  
  11.    
  12.        height = (a[0] << 8) + a[1]
  13.  
  14.    
  15.        a = img_file.read(2)
  16.  
  17.        
  18.        width = (a[0] << 8) + a[1]
  19.  
  20.    print("The resolution of the image is",width,"x",height)
  21.  
  22.  
  23. while True:
  24.    print("\n================= Find the Size of an Image =================\n\n")
  25.  
  26.  
  27.    jpeg_size("img.jpg")
  28.  
  29.    opt = input("\nDo you want to try again?(yes/no): ")
  30.  
  31.    if opt.lower() == 'yes':
  32.       ret=False
  33.    elif opt.lower() == 'no':
  34.       ret=True
  35.       print("Exiting program....")
  36.    else:
  37.       print("Please enter yes/no:")
  38.       break
  39.  
  40.    if ret == False:
  41.       continue

This program calculates the resolution of a JPEG image file by extracting its width and height directly from the file's binary data. It opens the image in binary mode, seeks to the location where the resolution information is stored (byte offset 163), and reads two sets of bytes to compute the height and width using bitwise operations. After determining the dimensions, it prints the resolution and prompts the user to either retry with the same file or exit. If the user chooses "yes," the process repeats; otherwise, it ends.

Output:

There you have it we successfully created How to Find the Size of an Image in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment