The SDL2_image library supports loading various common image formats, including:
To load an image, you can use the IMG_Load
 function:
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
SDL_Surface* loadImage(const char* path) {
SDL_Surface* surface = IMG_Load(path);
if (surface == nullptr) {
std::cout << "Failed to load image:"
<< IMG_GetError();
}
return surface;
}
int main(int argc, char** argv) {
return 0;
}
Make sure to initialize the SDL2_image library before loading images:
if (IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG) == 0) {
std::cout << "Failed to init SDL2_image:\n"
<< IMG_GetError();
// handle error
}
The IMG_Init
function takes a bitwise OR of the desired image format flags. In this example, we initialize support for PNG and JPEGÂ images.
Remember to free the loaded surface when you're done using it:
SDL_FreeSurface(surface);
By using SDL2_image, you can easily load and work with a variety of image formats in your SDL2Â projects.
Answers to questions are automatically generated and may not have been reviewed.
This step-by-step guide shows you how to set up SDL2 in an Xcode or CMake project on macOS