April 27th, 2010
SDL_image is a library that simplifies loading image files for SDL games. One of the more popular image file formats for games is PNG, and SDL_image has support for PNG. On game development message boards, you’ll find many questions from people having trouble loading PNG files with SDL_image. This trouble has two common causes.
The most common cause of trouble of PNG file loading is the operating system being unable to find the file. Suppose you have the following SDL_image function call in your code to load an image:
SDL_Surface* image; image = IMG_Load_RW("background.png", 1);
That code works only if the file background.png is in the current working directory. If the file isn’t in the current working directory, SDL_image won’t load it, and you have problems.
On Linux and Windows, the current working directory is the directory where the executable file is. Make sure your image files are in the same directory as the executable file.
On Mac OS X, SDL sets the working directory to the directory containing the application bundle. But your image files are in the Resources folder inside the application bundle. This means the code example to load background.png will not work on Mac OS X. The best solution is to change the working directory. My SDL Tips for Mac OS X post has instructions on changing the working directory.
The second common cause of PNG loading problems affects only Windows programmers. For SDL code to run on Windows, Windows must be able to find the SDL DLLs. To find the DLLs, they must reside either in the same directory as the executable file or in the windows\system32 directory.
To use SDL_image on Windows, you must add the SDL_image DLL to the same location as the SDL DLL. Most people remember to add the SDL_image DLL, but they discover PNG files will not load.
The reason the PNG files will not load is that loading PNG files with SDL_image on Windows requires the zlib and libpng DLLs as well as the SDL_image DLL. It’s an easy mistake to make, and the error message SDL_image returns isn’t very clear. The solution is to move the zlib and libpng DLLs to the same location as the SDL and SDL_image DLLs.