SDL Tutorial Series - Part 4 - How to Load and Display Images


In part 4 of this tutorial series, you will learn how to load an image from a file and display it on the screen using the SDL. This tutorial will build off of part 3 in this tutorial series so be sure you understood everything that was covered.

Arguably one of the most important parts of any video game are the graphics. The visuals are what will grab your players' attention and draw them into your video game. It is essential to creating a video game that you know how to properly display images on the players screen. We will be adding onto the code from part 3 so open the project in your compiler and we will begin.


First, find this line:

// Set the title bar
 SDL_WM_SetCaption("SDL Tutorial", "SDL Tutorial");

After it add this line:

// Load the image
SDL_Surface* image;
image = SDL_LoadBMP("gptutorials.bmp");
if (image == NULL)
{
     cerr << "SDL_LoadBMP() Failed: " << SDL_GetError() << endl;
     exit(1);
}

gptutorials
This is the image we will display on the screen. Right click on it and select 'Save image as'. Type in "gptutorials.bmp" without the quotes. Make sure where it says 'Save as type:' you select 'All Files'. This is very important! Save the bmp file in the same folder as your source code. If you named your project 'SDLTutorial', then it will be the 'SDLTutorial'->'SDLTutorial' folder. If you see your source code file (Main.cpp) in the folder then that is the correct folder. After you have done that find this line:
// Game loop will go here...
Right after that line add the following:
// Apply the image to the display
if (SDL_BlitSurface(image, NULL, display, NULL) != 0)
{
 cerr << "SDL_BlitSurface() Failed: " << SDL_GetError() << endl;
 exit(1);
}

//Update the display
SDL_Flip(display);
Alright, that is it! As you can see, the SDL makes complex tasks easy. All we had to do in order to load a bmp file was call one function. It does not get any easier than that. Your Main.cpp file should now look like this:
#include <iostream>
#include "SDL.h"

using std::cerr;
using std::endl;

int main(int argc, char* args[])
{
    // Initialize the SDL
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
 {
  cerr << "SDL_Init() Failed: " << SDL_GetError() << endl;
  exit(1);
 }

 // Set the video mode
 SDL_Surface* display;
 display = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
 if (display == NULL)
 {
  cerr << "SDL_SetVideoMode() Failed: " << SDL_GetError() << endl;
  exit(1);
 }

 // Set the title bar
 SDL_WM_SetCaption("SDL Tutorial", "SDL Tutorial");

// Load the image
 SDL_Surface* image;
 image = SDL_LoadBMP("gptutorials.bmp");
 if (image == NULL)
 {
     cerr << "SDL_LoadBMP() Failed: " << SDL_GetError() << endl;
     exit(1);
 }

 // Main loop
 SDL_Event event;
 while(1)
 {
  // Check for messages
  if (SDL_PollEvent(&event))
  {
   // Check for the quit message
   if (event.type == SDL_QUIT)
   {
    // Quit the program
    break;
   }
  }
  // Game loop will go here...
  // Apply the image to the display
  if (SDL_BlitSurface(image, NULL, display, NULL) != 0)
  {
 cerr << "SDL_BlitSurface() Failed: " << SDL_GetError() << endl;
 exit(1);
  }

  //Update the display
  SDL_Flip(display);

 }

    // Tell the SDL to clean up and shut down
    SDL_Quit();
    
    return 0;    
}
Make sure to save your progress. You should now be able to compile and run the program. Select 'Build' from the menu bar and click on 'Build Solution'. There should not be any errors or warnings. Now, select 'Debug' from the menu bar and click on 'Start Without Debugging'. You should see the window popup and the image applied in the upper left hand corner of the window. Lets look at the 3 functions we added to the program.
SDL_Surface *SDL_LoadBMP(const char* file);
This function loads the specified file into memory and converts it into an SDL_Surface structure which we can use for blitting to the screen. For now, do not worry about the SDL_Surface structure, we will examine it more in a future tutorial. If the function succeeds, it returns a valid pointer to an SDL_Surface structure. If it failed, it returns a NULL pointer and a description of the error can be obtained by calling SDL_GetError().
int SDL_BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect);
This function copies our image data to the screen. The first argument specifies where the image data is coming from and the third argument specifies where you want the data to go. In our case the source is the bmp file we loaded and the destination is the screen. You probably noticed we did not use the second and fourth arguments in this program. The second parameter (srcrect) can be used to blit sub-images from the source. The fourth argument can specify the position on the screen to copy the image to.
int SDL_Flip(SDL_Surface *screen);
Remember when we called SDL_Init(), we specified we wanted double buffering? This function will swap the buffers for us. This is not all that useful to us since we just copy a static image to the screen, but in future tutorials we will be adding animation. Double buffering is essential to animation to prevent flickering. I did not bother checking the return value of this function but you should. It returns -1 if there was an error or 0 on success. I leave adding error checking for this function as an exercise to the reader.

That is it for this tutorial. You now know how to display images on the screen by using the SDL library. This is essential to being able to program video games and we will build on this foundation in future tutorials. I hope you are enjoying using the SDL and can see the simplicity in its design. The next tutorial will introduce you to the SDL timing functions and how they can be used for simple animation.

Back to SDL Tutorial Index

Back to Main Page