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
- Import pygame
- Create an image object using pygame.image.load(“Provide image path here “) and store it in a variable.
- To get height of the image use image.get_height() method, here image is the variable in which image object is stored.
- Similarly, to get width of the image we use image.get_width() method, here image is the variable in which image object is stored.
- Print result.
Example:
Python3
import pygame
image = pygame.image.load( '/home/amninder/Pictures/Wallpapers/download.png' )
print ( "Height of image= " + str (image.get_height()))
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
- Import module
- Create a display object using display.set_mode() method.
- Load image to a variable using image.load() method.
- Using blit() method to draw the image on display surface object.
- Use get_size() method to display image width and height, this get_size() method returns width and height in tuples. Eg. (200,400).
- Use display.flip() to display content,i.e. anything that is drawn on the display surface object will be displayed on the window when the function is called in program.
Example:
Python3
import pygame as py
py.init()
window = py.display.set_mode(( 300 , 300 ))
py.display.set_caption( "GFG" )
image = py.image.load( '/home/amninder/Pictures/Wallpapers/download.png' )
print ( "size of image is (width,height):" , image.get_size())
while True :
window.blit(image, ( 0 , 0 ))
for event in py.event.get():
if event. type = = py.QUIT:
py.quit()
quit()
py.display.flip()
|
Output :
Using method 2
Last Updated :
24 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...