A Pygame Surface type represents an image. Images saved as files can be read in to a Pygame surface using the function pygame.image.load.
S = pygame.image.load(“image.png”)
There are other important functions to know about for images. There are others:
S.get _ size() – gets the image size, as a tuple (x,y)
S.copy() – Returns a copy of S
S.fill (color) – Fills the entire image with pixels of the specified color.
S.subsurface(r) – Return a part of a bigger surface. The pixels are shared, so changes in one will be seen immediately in the other. The variable r is a tuple (x, y, width, height) that defines a rectangular region in S to return.
There is a module named transform that contains methods for modifying surfaces. The most important methods are
pygame.transform.scale( Surface, (width, height) )
pygame.transform.rotate(Surface, angle)
Let’s take a break from the paint program and do a quick example with images. There is a file named “impression.jpg” that holds an impressionist image of a sunflower. It can be read into a Surface in a few lines of code and displayed within a short event loop. The image, named imgl, can be resized to be 100 x 100 pixels and drawn in a different location. Resizing is done as suggested above, using
img2 = pygame.transform.scale( img1, (100, 100) )
Finally, for this example, we’ll take a sub-image of imgland display it under the rescaled version:
img3 = img1.subsurface((200,200,200,200))
Each of these images can be displayed on the main Surface by blitting them to it as described above. The resulting canvas is shown in Figure 15.3.
import pygame
= pygame.display.set mode((1100, 900))
clock = pygame.time.Clock()
pygame.font.init()
imgl = pygame.image.load(“impression.jpg”)
img2 = pygame.transform.scale( imgl, (100,100) )
img3 = img1.subsurface((200,200,200,200))
while True:
clock.tick(10)
screen.fill((255,255,255))
screen.blit(img1, (0,0))
screen.blit(img2, (730, 100))
screen.blit(img3, (730, 300))
pygame.display.update()
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.