Images in Pygame

How to display Images in Pygame?


In previous post, we created an empty window for our game. In this post, let's add some images to our window.
In Pygame, Images are represented by a pygame object called as "surface". The Surface has a fixed resolution and pixel format
In previous post, when we wrote

Game_Window=pygame.display.set_mode((winWidth,winHeight))
it actually created a black surface with width= winWidth and height =winHeight. There is an Image module as well in pygame which has functions for loading and saving pictures, as well as transferring Surfaces to formats usable by other packages. There is no Image class; an image is loaded as a Surface object.
To show an image on the screen, you need to first load it into pygame. Here comes the Image module as follows:

let's say we want a background in our screen and we have a gameBkg.png file  with the background image that we are going to use. So Lets open our  GameScene.py file in your favorite editor.
Change the caption from "Empty Game Window" to "Image Test"

Now, add the following line to it below Game_Window definition.

background= pygame.image.load("gameBkg.png")

this is going lo load gameBkg.png and we'll get a surface with exactly same height and width of the background image. Now we have our image loaded we only have to display it on the screen. For that, add the following line just above your "while loop"

Game_Window.blit(background, (0, 0))

Here the blit() function coming from Surface module allows to draw a surface on another surface. We are drawing background on top of Game_Window here. The next parameter here is the position where you want to draw the surface(image) here (0,0) means top left corner of the Game_Window. the X axis here starts left to right and Y axis is top to bottom.

And that's how you show the images on pygame window. Currently my background image is this.


and my window is looking like this


I Can not see my background correctly because my background file is larger than my window. To fit our background image into our window, add the following  line below background definition.

background=pygame.transform.scale(background,(winWidth,winHeight))

in this way we scale the image to desired size.
now if i run the code, my game window will look like


and yeah,we got how to display images on window.

so finally our code is looking like
 
Stay tuned for next post where we'll see some more things we can do with images.

1 comment:

Your comments and suggestions are valuable and are always welcome and will be helpful to me to create a good quality content. Please leave your thoughts