سؤال

After fixing various other SDL errors, (both with SDL itself and SDL_Image) I have written this error-free code:

#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include <string>

using namespace std;

#define null 0

SDL_Window *window = nullptr;
SDL_Renderer *renderer = nullptr;

SDL_Texture* LoadImage(string file)
{
    SDL_Texture *texture = nullptr;

    texture = IMG_LoadTexture(renderer, file.c_str());
    if (texture == nullptr)
        cout << "Failed to load image: " + file + IMG_GetError();
    return texture;
}

void ApplySurface(int x, int y, SDL_Texture *textureArgument, SDL_Renderer *rendererArgument)
{
    SDL_Rect pos;
    pos.x = x;
    pos.y = y;
    SDL_QueryTexture(textureArgument, null, null, &pos.w, &pos.h);
    SDL_RenderCopy(rendererArgument, textureArgument, null, &pos);
}

int main(int argc, char* argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING))
        return 1;

    window = SDL_CreateWindow("ShitHappens", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    SDL_Texture *image = nullptr;
    image = LoadImage("image.png");

    SDL_RenderClear(renderer);

    int iW, iH;
    SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
    int x = 640 / 2 - iW / 2, y = 480 / 2 - iH / 2;

    ApplySurface(x, y, image, renderer);
    SDL_RenderPresent(renderer);

    SDL_Delay(2000);
    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    return 0;
}

Which still does not display the image in question. I have tried replacing the functions with the SDL_LoadBMP() image and it succeeded, it even works if I load a BMP image through the current code, yet not a PNG image.

هل كانت مفيدة؟

المحلول

If BMP files load and PNG files don't load on Windows, you have a DLL location problem. To load PNGs properly on Windows, SDL_image requires that the libpng and zlib DLLs reside in the same directory as the executable. The Windows version of SDL_image uses libpng and zlib to load PNG files so you have to place those DLLs in the right directory. Just having the SDL_image DLL in the same directory as the executable isn't enough.

نصائح أخرى

I had the same error and used the advice @MarkSzymczyk gave above. I simply hadn't added all the dll needed to the project folder. So I added all these:

  1. SDL2_image.dll
  2. libjpeg-9.dll
  3. libpng16-16.dll
  4. libtiff-5.dll
  5. libwebp-7.dll

Then my image loaded. I think that I needed only the SDL2_image and libpng16-16 dlls but I added all of them for future use.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top