SDL (Simple DirectMedia Layer) - Rendering other image formats
Rendering other image formats requires the use of another SDL library: SDL_image
. However, the process of rendering different image formats is very much the same as rendering BMP images. In this section, we'll demonstrate how to render a PNG file onto a window.
You can download the source code of this section in this GitLab repository. All source code is stored in this group.
Importing the SDL_image
library
[edit | edit source]We'll import the SDL_image
library, in wikibook.h
, in the following fashion:
#ifdef _WIN32
#include <SDL/SDL.h> /* Windows-specific SDL2 library */
#include <SDL_image.h>
#else
#include <SDL2/SDL.h> /* macOS- and GNU/Linux-specific */
#include <SDL2/SDL_image.h>
#endif
Initialising the image subsystem
[edit | edit source]Right after initialising the SDL subsytems, we would need to initialise the image subsystem using IMG_Init
. Given the parameter int flags
, it returns flags
on success.
We'll want to render a PNG file so we would want to use the flag IMG_INIT_PNG
. There are other flags like IMG_INIT_JPG
(check IMG_Init
for more information). To initialise multiple flags use the |
OR operator, for example:
const int FLAGS = IMG_INIT_PNG | IMG_INIT_JPG;
You'll also have to use IMG_Quit
to close the subsystem.
/* Initialise SDL_image */
const int FLAGS = IMG_INIT_PNG;
if (IMG_Init(FLAGS) != FLAGS) {
fprintf(stderr, "SDL_image failed to initialise: %s\n", IMG_GetError());
return -1;
}
/* Automatically execute IMG_Quit at exit */
atexit(IMG_Quit);
Since we're using SDL_image
, we have to use IMG_GetError
in place of SDL_GetError
.
Loading the image
[edit | edit source]Loading the image is very simple, just use the IMG_Load
function on a SDL_Surface
. Like with IMG_Init
, we must use IMG_GetError
.
wb->image = IMG_Load(WB_IMAGE_PATH);
if (wb->image == NULL) {
fprintf(stderr, "WikiBook failed to load image: %s\n", IMG_GetError());
return -1;
}
Remember, to make sure that the file path to the image is correct, i.e. WB_IMAGE_PATH
! We're rendering a PNG image!