How to Get the Dimensions of an Image in Python
In this tutorial, you will learn how to get the Dimensions of an Image in Python. For this, we use Python Imaging Library (PIL) Module. PIL consists of various Classes. We require only Image Class to get the Dimensions of an Image. So, we have to import Image Class from PIL.
Hence, the first line of Our Script will be
from PIL import Image
Image Class is used to perform Certain Operations like Opening an Image, Saving an Image, Cropping an Image etc. Lets have a look at Opening an Image.
The open() method in Image class is used to Open an Existing Image at Specified Path (i.e.”Path_to_Your_Image”). Where, img is the Image Object which is used to perform Operations on Image. Image class consists of an attribute named size (i.e. img.size). Lets have a glance over size attribute in Image Class.
Size is Two Valued Tuple. It is tuple of Width and Height of an Image. i.e. size=(W,H)
W is the Width of an Image
H is the Height of an Image.
Here, W is unpacked from size and copied into the w. Similarly, H is unpacked from size and copied into the h. Hence, we obtain the Dimensions of an Image.size gives the Values of Width and Height of an Image in Pixels. So, It returns the Integers denoting Width and Height of an Image.
Hence, Our Code will be as follows
from PIL import Image img=Image.open("Path_to_Your_Image") w,h=img.size # w=Width and h=Height print("Width =",w,end="\t") print("Height =",h)
w is the Width of an Image
h is the Height of an Image
Width = 1366 Height = 768
In this way, we can find the Dimensions of an Image. For further reference on Image class and Size Attribute Click Here ->Size – Image – PIL
You can also read Change the Brightness of an Image