Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 41 ยท Drawing and Images

Images and Transforms in Pygame

Load and display images in Pygame, read their size, scale, rotate and flip them, rotate around the center, make an image face the mouse, and cache transformed images.

Shapes and text only get you so far. Real games show sprites, backgrounds, icons and tiles, which means loading image files and often changing them: making them bigger, turning them, mirroring a character to face left. This lesson covers loading, the transform module and the one trap everyone falls into, rotating an image around its center.

Loading and drawing an image

Python
player = pygame.image.load("assets/player.png").convert_alpha()
background = pygame.image.load("assets/sky.jpg").convert()

screen.blit(background, (0, 0))
screen.blit(player, (100, 200))
  • pygame.image.load(path) reads PNG, JPG, GIF, BMP, WebP and more, and returns a Surface.
  • Call .convert_alpha() for images with transparency (PNG sprites) and .convert() for opaque ones. Both must be called after set_mode(). See Surfaces and Blitting.
  • Load every image once, before the loop, never per frame.

Paths that work anywhere

A relative path like "assets/player.png" is relative to the folder you started Python from, not to the script. Build paths from the script's location so the game runs from anywhere:

Python
from pathlib import Path

BASE = Path(__file__).parent
player = pygame.image.load(BASE / "assets" / "player.png").convert_alpha()

If a file is missing you get FileNotFoundError; if it is corrupted or an unsupported format, pygame.error. Wrap loading in a function that reports the file name to make debugging easy.

Image size

Python
width, height = player.get_size()
rect = player.get_rect(topleft=(100, 200))
screen.blit(player, rect)

get_width() and get_height() also exist. The rect is the standard way to keep an image's position.

Try it: save, load and inspect

Here the runner has no assets folder, so we paint a small image, save it to a file, load it back with pygame.image.load, and inspect it. This is the same API you use with real files.

Python Save and load an image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The transform module

Every function in pygame.transform returns a new Surface; the original is unchanged.

Function Effect
scale(surface, (w, h)) Resize to an exact size (fast, nearest neighbor)
smoothscale(surface, (w, h)) Resize with smoothing (better for photos and downscaling)
scale_by(surface, factor) Resize by a factor (pygame-ce)
rotate(surface, angle) Rotate counter-clockwise by degrees; the result may be bigger
rotozoom(surface, angle, scale) Rotate and scale together with smoothing
flip(surface, flip_x, flip_y) Mirror horizontally and/or vertically
Python
small = pygame.transform.scale(image, (32, 32))
half = pygame.transform.smoothscale_by(image, 0.5)
left_facing = pygame.transform.flip(right_facing, True, False)

Flipping horizontally is how one drawing of a character serves for both directions.

Try it: scale, rotate and flip

An asymmetric "F" shape makes the effect of each transform visible.

Python Transforms on an F

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rotating around the center

rotate() returns a surface big enough to contain the rotated image. At 45 degrees a square image grows noticeably, and the new surface's top-left is not where the old one's was. If you keep blitting at the old position, the image appears to wobble around its corner.

The fix is to rebuild the rect with the same center after every rotation:

Python
rotated = pygame.transform.rotate(original, angle)
rect = rotated.get_rect(center=old_center)
screen.blit(rotated, rect)

Also always rotate the original image, not the previous result. Rotating a rotated image repeatedly blurs it and makes it grow.

Python Sizes change; the center stays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The size changes with the angle, the center is constant and the top-left moves, which is exactly what the rect correction handles.

Making an image face the mouse

Turn a sprite toward a target with vector math. Vector2.angle_to(other) returns the angle in degrees that you would have to turn the first vector to point along the second. Measured from the direction to the target back to the "facing right" vector, it is exactly the counter-clockwise angle that rotate expects, even though the screen's y axis points down:

Python
mouse = pygame.Vector2(pygame.mouse.get_pos())
direction = mouse - pygame.Vector2(player_rect.center)
angle = direction.angle_to(pygame.Vector2(1, 0))   # image drawn pointing right
rotated = pygame.transform.rotate(player_image, angle)
screen.blit(rotated, rotated.get_rect(center=player_rect.center))

The sign depends on which way your artwork points. If the sprite turns the wrong way, flip the sign or add an offset (90 for artwork pointing up).

Python Aim angle toward a target

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A target straight up gives 90 (a quarter turn counter-clockwise from "facing right") and straight down gives 270. Those are the values you pass to rotate.

Scaling for display and speed

  • Scale images once at load time (image = pygame.transform.scale(image, (64, 64))), not every frame.
  • Use smoothscale when shrinking photos or backgrounds; use scale for pixel art.
  • If you need many rotation angles (say, a spinning coin), pre-render a list of rotated frames at start-up and index into it.
  • Transform results are new surfaces, so cache them in variables instead of recomputing for the same input.

Icons, colorkey and saving

Set the window icon with pygame.display.set_icon(image). Images without alpha can use a colorkey with image.set_colorkey((255, 0, 255)) to turn magenta transparent. Save screenshots with pygame.image.save(screen, "shot.png"). A sprite sheet is a single image sliced with blit(..., area=rect) or subsurface; animation with sprite sheets is covered later in the course.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do the functions in pygame.transform return?

    Transforms never change the original. Assign the result to a variable.
  2. 2. Why does a rotating image seem to wobble around its corner?

    Create a new rect with the same center: rotated.get_rect(center=old_center).
  3. 3. Why should you always rotate the original image rather than the previous result?

    Each rotation resamples pixels and enlarges the canvas, so errors accumulate.
  4. 4. How do you mirror a sprite horizontally?

    The two booleans of flip select horizontal and vertical mirroring.
  5. 5. When should convert_alpha() be used?

    It converts to a fast pixel format and keeps per-pixel alpha. It needs an existing display.

Summary

  • Load images once with pygame.image.load(path) and convert() or convert_alpha().
  • Use get_size() and get_rect() for dimensions and position.
  • scale, smoothscale, rotate, rotozoom and flip return new surfaces.
  • After rotating, rebuild the rect from the same center, and rotate the original each time.
  • Cache scaled and rotated results instead of recomputing every frame.

Next: Moving Objects and Boundaries