Getting width and height of an image in 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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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.
- 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.
Method 2 : Using get_size() :
This function is capable of returning dimensions of the image provided to it as reference as a tuple.
- 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.