Can't load image with IMG_Load()

浪尽此生 提交于 2020-01-15 15:58:07

问题


I've got a problem with the SDL_image library. I wrote a simple program loading a spritesheet and animating it on left-click. Here's the code:

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

const int sw=800;
const int sh=450;

int main(){
    SDL_Init(SDL_INIT_EVERYTHING);
    IMG_Init(IMG_INIT_PNG);

    bool quit=false;
    bool shoot=false;
    SDL_Event event;
    Uint32 time;
    unsigned  char frame=0;


    SDL_Window* window = SDL_CreateWindow("Sprite",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,sw,sh,0);
    SDL_Renderer* render = SDL_CreateRenderer(window,-1,0);

    SDL_Surface* image = IMG_Load("p_pt_12.png");
    printf("IMG_Load: %s\n", IMG_GetError());

    SDL_Texture* texture = SDL_CreateTextureFromSurface(render, image);

    while(!quit){
        if(shoot){
            time=SDL_GetTicks();
            time/=(750/5);
            frame=time%5;
            if(frame==4){
                frame = 0;
                shoot=false;
            }
        }
            SDL_Rect srcrect = { frame*96,0,96,96};
            SDL_Rect dstrect = { (sw-96)/2, (sh-96)/2, 96, 96 };


        SDL_PollEvent(&event);
        switch (event.type){
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_MOUSEBUTTONDOWN:
                if(event.button.button == SDL_BUTTON_LEFT) shoot = true;
                break;
        }

        SDL_RenderClear(render);
        SDL_RenderCopy(render, texture,&srcrect,&dstrect);
        SDL_RenderPresent(render);
    }

    SDL_DestroyTexture(texture);
    SDL_FreeSurface(image);
    SDL_DestroyRenderer(render);
    SDL_DestroyWindow(window);
    IMG_Quit();
    SDL_Quit();

    return 0;
}    

The problem is when I try to run it, IMG_Load() returns NULL pointer and IMG_GetError() says "Unsupported file format". The spritesheet is a .png file, but the same happens with .jpg spritesheet. I'm sure, that the code is correct, because it works on other device with exactly the same image file like a charm. I've tried reinstalling SDL and SDL_image, but it doesn't work. SDL_RWops and IMG_LoadPNG_RW doesn't help neither. I'm using Eclipse Kepler SR2 (but I've also tried to run it with Code::Blocks 12.11 with the same result) on 64-bit Linux Mint.

I will appreciate any kind of help, thanks!


回答1:


Your code is correct and works for me. Probably your system is missing some libraries needed by sdl_image to handle images, such as libpng and zlib. Install them and let us know if it worked.



来源:https://stackoverflow.com/questions/23323450/cant-load-image-with-img-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!