Open In App

Getting width and height of an image in Pygame

Prerequisites: Pygame

To use graphics in python programs we use a module called Pygame. Pygame provides high functionality for developing games and graphics in Python. Nowadays Pygame are very much popular to build simple 2D games. In order to run a program written in Python using Pygame module, a system must have Python installed with Pygame module. 



Following are the examples and steps needed to import the image using Pygame and get the height and width of that image.

Image in used : Link to the image 



Dimensions : 200×200

 

 

Method 1 : Using get_width() and get_height() :

The name of the function is explanatory enough as to what they are used for.

Approach

Example:




# import pygame
import pygame
  
# creating image object
image = pygame.image.load('/home/amninder/Pictures/Wallpapers/download.png')
  
# get_height method return the height of the surface pixel,
# in our case surface is image
print("Height of image= " + str(image.get_height()))
  
# get_width method return the width of the surface pixel,
# in our case surface is image
print("Width of image= " + str(image.get_width()))

Output:

Method 1

 

Method 2 : Using get_size() :

This function is capable of returning dimensions of the image provided to it as reference as a tuple.

Approach

Example:




import pygame as py
  
# Initiate pygame and the modules that comes with pygame
py.init()
  
# setting frame/window/surface with some dimensions
window = py.display.set_mode((300, 300))
  
# to set title of pygame window
py.display.set_caption("GFG")
  
# creating image object
image = py.image.load('/home/amninder/Pictures/Wallpapers/download.png')
  
# to display size of image
print("size of image is (width,height):", image.get_size())
  
# loop to run window continuously
while True:
    window.blit(image, (0, 0))
  
    # loop through the list of Event
    for event in py.event.get():
        # to end the event/loop
        if event.type == py.QUIT:
  
            # it will deactivate the pygame library
            py.quit()
            quit()
  
        # to display when screen update
        py.display.flip()

Output :

Using method 2


Article Tags :