[ SDL2 — Part 7] Loading png files

Ole Vegard Mythe Moland
3 min readJan 22, 2022

Using PNG

In the previous post we learned how to load .bmp files. Which is not optimal. The .bmp format means the files grow large and there is no `alpha layer` ( no transparency. ) Which means you end up with ugly opaque edges instead of transparency

How ot looked before vs how it’ll look with texture that has alpha layers

SDL 2 Image

Up until now, we’ve only been using the standard base SDL 2. But the standard SDL 2 doesn’t support loading of .png files. But fortunately, there is an SDL 2 library that does this. And since it’s still SDL 2, it will work perfectly with or other SDL code!

Linux

For Linux you can use need to install lSDL2_imageor libSDL2_image ( the actual name might be different in different distributions. )

The linker flag is -lSDL2_image

The process is more or less identical to that of setting up SDL2 base. For more information, see my post about setting up SDL2.

Windows

Similar to setting up SDL2 base. The difference is that you have to download the development files for SDL2_image. And similarly add SDL2_image.lib to library includes and add SDL2_image.lib to the library flags ( where you previously added SDL2.lib )

Mac

See the first post of my tutorial. Just install SDL2_image instead of SDL 2.

Loading PNGs using SDL2_image

In order to use SDL2_image, you need to add the header file, like so :

#include <SDL2/SDL_image.h>

The actual loading of .png files is just as easy as loading .bmp files. But since it uses an extension library, we have to use a different function :


SDL_Texture* IMG_LoadTexture (
SDL_Renderer* renderer,
const char *file
);

This function will load a file and return it as a SDL_Texture*. This means we don’t have to convert it, so we can just do:

SDL_Texture* LoadTexture( const std::string &str ){    // Load image as SDL_Surface
SDL_Texture* texture = IMG_LoadTexture( renderer, str.c_str() );
if ( texture == nullptr ) {
std::cout << “Failed to load texture “ << str << “ error : “ << SDL_GetError() << std::endl;
return nullptr;
}
return texture;
}

Note that this function, unlike the one for loading bmpfiles, needs a pointer to the SDL_Renderer this is because it returns a hardware optimized SDL_Texture, and SDL 2 needs the SDL_Renderer to do the actual hardware optimization.

Running it

Just like last time, I’m not gonna show the entire code as one long gist ( too much code, and there are images too. ) Here is a link to the code in .zip form

Linux / Mac

If you are compiling using the compiler, you have to add -lSDL2_image to the compile string like so :

clang++ main.cpp -std=c++11 -o Game -lSDL2 -lSDL2_image

If you want to run it, you simply do

./Game
This is how the game should look

Conclusion

That’s all the extra work needed to load png files. I’m not sure why it’s not supported by the base library, but after getting it set up, it’s easy to use.

Next part

You can find the next part here.

--

--