Introduction
Pygame library is one of the Python programming libraries with very efficient functionalities such as building custom events, taking input from the user through the keyboard, creating custom input boxes for inputs, etc. This article will discuss the pygame blit() function and how to use the pygame blit() function to place an image on the screen. I hope you will enjoy the article!
Pygame blit()
The Pygame blit() method is one of the methods to place an image onto the screens of pygame applications. It intends to put an image on the screen. It just copies the pixels of an image from one surface to another surface just like that.
This blit() method is packaged in the pygame surface module.
The syntax of the blit() mentioned in its official documentation is as follows:
→ blit(source, dest, area=None, special_flags=0)
We can observe that it draws an image from the source surface to the destination surface. It returns a rectangle that is used as the position for the blit. An optional area attribute is also introduced to set the area of the rectangle to be formed. This return rectangle is the area of the affected pixels of an image, excluding any pixels outside the destination surface.
How to use blit()?
In order to use the blit() method, we need an image object that is already created.
To create an image object and load an image into it - we can use the load() method that is packaged in the pygame image module.
-→ image = pygame.image.load(“sample.jpg”)
This will load the image to the object image.
Now to blit the image to the screen, we can code it as follows:
→ screen.blit(image, (100, 100))
Now, this code will blit the image onto the screen. The position of the image will be 100, 100 from the top-left corner of the screen. As we know, just doing this doesn’t reflect any changes to the pygame application. We need to update the pygame application to see our changes so far.
For that, we can use either display.flip() or display.update() to update the changes.
→ pygame.display.update()
After this, we can able to see the image that is loaded on the screen of our pygame application.
Simple pygame program to load and display an image suing blit():
import pygame
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode((600, 600)) #Set the size of the screen using the #pygame.display.set_mode().
img = pygame.image.load(“sample.jpg”) #load the image
window.blit(image, (100, 100)) #blit
pygame.display.update() #update the screen.
This will display the sample.jpg image on your screen. You can also refer to the official documentation of the pygame blit() method to get more information.
Also Read - Image Sampling