Search code examples
cbmpimage-loadingsdl-image

Issue loading BMP image using SDL_image


I am new to SDL_image and I am trying to use it in a C file to load a BMP image. To that end, I have written the following code:

#include "SDL/SDL.h"
#include "SDL_image.h"

SDL_RWops *rwop;
rwop = SDL_RWFromFile("sample.bmp", "rb");

However, for some reason, although rwop after those lines are executed is not NULL anymore, IMG_isBMP(rwop) is 0.

Any idea what could be wrong?


Solution

  • Perhaps better example. This (might) yield more information and perhaps if BMP is supported:

    https://www.libsdl.org/projects/SDL_image/docs/SDL_image_32.html

    You could also try using IMG_LoadBMP_RW as per example here:

    https://www.libsdl.org/projects/SDL_image/docs/SDL_image_16.html#SEC16

    #include <stdio.h>
    
    #include "SDL/SDL.h"
    #include "SDL/SDL_image.h"
    
    int main(int argc, char *argv[])
    {
        const char *fn = "sample.bmp";
        SDL_Surface *surf;
    
        if (argc > 1)
            fn = argv[1];
    
        if ((surf = SDL_LoadBMP(fn)) == NULL) {
            printf("SDL_loadBMP failed: %s\n", SDL_GetError());
            SDL_Quit();
            return 1;
        }
    
        printf("%s is bmp\n", fn);
    
        SDL_FreeSurface(surf);
        SDL_Quit();
    
        return 0;
    }
    

    Old answer:


    Tested and validated:

    #include <stdio.h>
    
    #include "SDL/SDL.h"
    #include "SDL/SDL_image.h"
    
    int main(int argc, char *argv[])
    {
        const char *fn = "sample.bmp";
        int v;
        SDL_RWops *rwop;
    
        if (argc > 1)
            fn = argv[1];
    
        if ((rwop = SDL_RWFromFile(fn, "rb")) == NULL) {
            printf("SDL_RWFromFile failed: %s\n", SDL_GetError());
            SDL_Quit();
            return 1;
        }
    
        v = IMG_isBMP(rwop);
    
        printf("%s is bmp = %d\n", fn, v);
    
        SDL_FreeRW(rwop);
        SDL_Quit();
    
        return 0;
    }
    

    Compiled with:

    gcc -Wall -Wextra -pedantic -o sdl sdl.c `sdl-config --libs` -lSDL_image
    

    Yield for BMP images, e.g.:

    $ ./sdltest lena.bmp 
    lena.bmp is bmp = 1