Menu
CoddyTech

Load an Image

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 1 of 39.

Games draw pictures, not only shapes. A picture comes from an image file, and pygame turns the file into a Surface, the same kind of thing as the window: a grid of pixels you can draw.

ship = pygame.image.load("assets/images/ship.png").convert_alpha()

The path is relative to main.py: the game has an assets folder next to it, and the Assets tab beside the game lists every file in it.

convert_alpha() copies the picture into the window's own pixel format, so drawing it every frame is fast, and keeps its see-through pixels. It needs the window, so load images after set_mode. Load each image once, before the loop: reading a file 60 times a second slows the game down.

To draw the picture, blit it onto the window. The position is where its top left corner goes:

screen.blit(ship, (288, 208))

Blit it after screen.fill(...), or the fill paints over it.

challenge icon

Challenge

Easy

Show the ship image in the middle of the window.

  1. After set_mode, load assets/images/ship.png with .convert_alpha() into a variable named ship.
  2. In the loop, after the fill, blit ship with its top left corner at (288, 208).

Press Play: the 64 by 64 ship sits in the middle. Then Check.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Space Images")
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((20, 22, 40))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground