How to to load BMP image into a window using SDL2 in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <SDL.h>

static SDL_Surface* bmp = NULL;
static SDL_Surface* screen = NULL;
static SDL_Window* window = NULL;

bool init() {
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		printf("SDL_Init Error: %s\n", SDL_GetError());
		return false;
	}
	else {
        window = SDL_CreateWindow("SDL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                         800, 600, SDL_WINDOW_SHOWN);
        if (window == NULL)	{
			printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
            return false;
		}
		else {
            screen = SDL_GetWindowSurface(window);
		}
	}

	return true;
}

bool loadBMP() {
    bmp = SDL_LoadBMP("assets/RAY.BMP");

    if (bmp == NULL) {
        printf("SDL_LoadBMP Error: %s\n", SDL_GetError());
        return false;
    }

    return true;
}

void close() {
    SDL_FreeSurface(bmp);
    bmp = NULL;

    SDL_DestroyWindow(window);
    window = NULL;

    SDL_Quit();
}

int main(int argc, char* argv[]) {
	if (!init()) {
		printf("init error\n");
	}
	else {
		if (!loadBMP()) {
			printf("loadBMP Error\n");
		}
		else {
			SDL_BlitSurface(bmp, NULL, screen, NULL);

			SDL_UpdateWindowSurface(window);

			SDL_Event event; 
			bool quit = false; 
			while (quit == false) { 
				while (SDL_PollEvent(&event)) { 
					if (event.type == SDL_QUIT) 
						quit = true; 
				} 
			}
		}
	}
	close();

    return 0;
}

 



answered Jul 24, 2023 by avibootz
edited Jul 24, 2023 by avibootz
...