Algorithm
-
Import the necessary libraries:
pythonfrom PIL import Image
-
Open the image file using the
Image.open()
method:pythonimage_path = "path/to/your/image.jpg" # Replace with the actual path to your image file img = Image.open
(image_path)
Get the size (resolution) of the image using thesize
attribute of the image object:pythonwidth, height = img.size
-
Print or use the width and height as needed:
pythonprint(f"Width: {width}px, Height: {height}px")
Code Examples
#1 Code Example- Python Program to Find the Size of Image Using PIL
Code -
Python Programming
# Python Program to Find the Size of Image Using PIL
#importing the module
import PIL
from PIL import Image
# loading the image
img = PIL.Image.open("img.png")
# fetching the dimensions
Width, height = img.size
# displaying the dimensions
print("the dimensions are :", str(width) + "x" + str(height))
Copy The Code &
Try With Live Editor
Output
the dimensions are :500x130
#2 Code Example- Python Program to Find the Size of Image Using OpenCV
Code -
Python Programming
# Python Program to Find the Size of Image Using OpenCV
# importing the module
import cv2
# loading the image
img = cv2.imread("geeksforgeeks.png")
# fetching the dimensions
w = img.shape[1]
h = img.shape[0]
# displaying the dimensions
print(“the dimensions are :”, str(w) + "x" + str(h))
Copy The Code &
Try With Live Editor
Output
the dimensions are :450x140
#3 Code Example- Python Program to Find the Size of Image
Code -
Python Programming
# Python Program to Find the Size of Image
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# 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 resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")
Copy The Code &
Try With Live Editor
Output
The resolution of the image is 280 x 280
Demonstration
Python Programing Example to Find the Size (Resolution) of a Image-DevsEnv