How to load JPG/PNG Textures in an SDL/OpenGL App under OSX
SDL 2 SDL_image minimal runnable example
main.c
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
int main(void) {
SDL_Event event;
SDL_Renderer *renderer = NULL;
SDL_Texture *texture = NULL;
SDL_Window *window = NULL;
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
SDL_CreateWindowAndRenderer(
500, 500,
0, &window, &renderer
);
IMG_Init(IMG_INIT_PNG);
texture = IMG_LoadTexture(renderer, "flower.png");
while (1) {
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
break;
}
SDL_DestroyTexture(texture);
IMG_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
GitHub upstream.
Compile and run:
sudo apt-get install libsdl2-dev libsdl2-image-dev
gcc -std=c99 -o main -Wall -Wextra -pedantic main.c -lSDL2 -lSDL2_image
./main
Outcome:
Tested on Ubuntu 16.04, GCC 6.4.0, SDL 2.0.4, SDL Image 2.0.1.
Have a look at the SDL_image library. It offers functions like IMG_LoadPNG
that load your picture "as an" SDL_Surface.
Since you already work with SDL this should fit quite well in your program.
Sample taken from the SDL_image documentation:
// Load sample.png into image
SDL_Surface* image = IMG_Load("sample.png");
if (image == nullptr) {
std::cout << "IMG_Load: " << IMG_GetError() << "\n";
}