Create your own game
eng   рус

SDL2 loading images (bmp, jpg, png)

Previous tutorial: Hello World in Python SDL2
Next tutorial: Textures in SDL2
SDL2 loading images (bmp, jpg, png)

In previous tutorial we learned how to create surface of one color with SDL2 in Python programming language. Colored rectangles are good things and pleasant to the eye, but when we mention 2d graphics we imagining sprites of Mario, Battle City, Lode Runner and other classic games. In this tutorial we'll learn how to load images in our programs. At the end of tutorial we'll be able to load images of different formats: bmp, jpg/jpeg, png.

SDL_LoadBMP function

SDL2 natively can load only bmp files. There is a function SDL_LoadBMP that accepts file name as argument:

new_surface = sdl2.SDL_LoadBMP(b"tank.bmp")

Then we can use new_surface variable like any other surface. If you blit it to the window surface, you'll see the image that bmp file contained on the screen.

BMP format has two flaws: bmp format is uncompressed, that means it occupies large amount of memory. But that would be ok if bmp would support transparency. And that's the second problem of bmp - it doesn't support transparency. We can only manually make it transparent by choosing key color and set alpha channel of each such pixel to zeroes. Hopefully SDL2 may load other formats.

SDL_image 2.0 library

SDL has additional library for working with images. It's called SDL_image. To use it you need to download dll additionally to SDL2 itself. In Python programming language SDL_image is namespaced in sdl2.sdlimage module. Now let's load png file:

import sdl2.sdlimage # init code image_surface = sdl2.sdlimage.IMG_Load(b"tank.png")

On the image on top of this tutorial you can see magnified screenshot of my tank. I'm not an artist as you can see. SDL_image supports transparency (actually png format supports it and SDL_image just properly loads the image). So if I change the background, the tank will look like this:

I've just draw the contour of the tank. You can draw any image you want.


In this tutorial we saw how SDL loads different types of image formats. In future tutorials we'll learn the difference between formats and how they are encoded. The easiest one is bmp - it stores uncompressed data, so it's easy write such file. png and jpg use compression, so to understand them we need understand algrorithms and math they use. But that will be not soon and in next tutorials we'll learn about textures in SDL and how to rotate images.


No comments yet