SDL_image

SDL is deliberately designed to provide the bare bones of creating a graphical program. As such, it doesn't provide methods for loading various image formats into your program. That's where a library like SDL_image comes in. Using SDL_image you can load in the popular image formats such as BMP, PNM (PPM/PGM/PBM), XPM, LBM, PCX, GIF, JPEG, PNG, TGA, and TIFF formats. These are loaded onto your SDL_Surface and painted onto the screen as normal. It supports alpha transparency for those file formats that store it (eg PNG).

This documentation is extracted from the documentation page (written by Jon Atkins), which may contain more up to date information. For a copy of SDL_image, see the official page.

API

It's pretty simple really. All you do is put the include at the top, make your SDL_Surface as usual, and then use one of three methods to access your beautiful image file.

#include "SDL_image.h"

SDL_Surface *IMG_Load(const char *file);    // or,
SDL_Surface *IMG_Load_RW(SDL_RWops *src, int freesrc);  // or,
SDL_Surface *IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, char *type);

where "type" is a string specifying the format (i.e. "PNG" or "pcx"). Note that IMG_Load_RW cannot load TGA images.

To create a surface from an XPM image included in C source, use:

SDL_Surface *IMG_ReadXPMFromArray(char **xpm);

JPEG support requires the JPEG library:

PNG support requires the PNG library and the Zlib library:

TIFF support requires the TIFF library:

Under Windows, having these libraries simply means downloading the DLL file and placing it in the same folder as your program. Linux users will need to place the files in their lib directory... the sites should have instructions on where to put them exactly.

Example code

Here is some example code of how to use SDL_image.h:

int DrawImage( SDL_Surface *surface, char *image_path, int x_pos, int y_pos )
{
   SDL_Surface *image = IMG_Load ( image_path );
   if ( !image )
   {
      printf ( "IMG_Load: %s\n", IMG_GetError () );
      return 1;
   }

   // Draws the image on the screen:
   SDL_Rect rcDest = { x_pos, y_pos, 0, 0 };
   SDL_BlitSurface ( image, NULL, surface, &rcDest );

   // something like SDL_UpdateRect(surface, x_pos, y_pos, image->w, image->h); is missing here

   SDL_FreeSurface ( image );
   return 0;
}

SDL_image (last edited 2009-04-09 08:51:39 by a1)