2

I'm trying to load images using SDL2-image, it works when I try to load a .png, but it fails to recognize a .jpg

My imports:

#include <SDL2/SDL.h>
#undef main
#include <SDL2/SDL_image.h>
#include "logger.hpp"

And my code:

int main(int argc, char **argv) {
  if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    logger::Log(logger::DEBUG, "Could not initialize SDL (%s)", SDL_GetError());
  }
  int flags = IMG_INIT_JPG | IMG_INIT_PNG;
  int initRes = IMG_Init(flags);
  if (initRes & flags != flags) {
      logger::Log(logger::DEBUG, "IMG_Init: Failed to init required jpg and png support!");
      logger::Log(logger::DEBUG, "IMG_Init: %s", IMG_GetError());
  }
  else logger::Log(logger::DEBUG, "JPG AND PNG SUPPORTED");
  SDL_Surface* surface = IMG_Load("image.jpg");
  if (!surface) {
      logger::Log(logger::DEBUG, "surface error: %s", IMG_GetError());
  }
  else {
      logger::Log(logger::DEBUG, "LOADED");
  }
...
}

Which gives me

JPG AND PNG SUPPORTED
surface error: Unsupported image format

There are installed and integrated via vcpkg: SDL2-image, libjpeg-turbo, libpng and zlib, so I basically have no idea why this is happening

  • 1
    Try `if ((initRes & flags) != flags)` – Alan Birtles May 13 '22 at 06:11
  • 1
    Note that jpeg support is an optional feature: https://vcpkg.info/port/sdl2-image – Alan Birtles May 13 '22 at 06:12
  • It might be an [*operator precedence*](https://en.cppreference.com/w/cpp/language/operator_precedence) issue. `initRes & flags != flags` is really the same as `initRes & (flags != flags)` which will *always* be false. – Some programmer dude May 13 '22 at 06:15
  • 2
    Really, it is a check misguidance, which is for some reason present in official SDL2-image docs (https://www.libsdl.org/projects/SDL_image/docs/SDL_image.pdf) on page 10 of the document. Solved by reinstalling SDL2-image with libjpeg-turbo as feature as vcpkg install sdl2-image[libjpeg-turbo] – Ilya3point999k May 13 '22 at 06:28

1 Answers1

1

Due to operator precedence initRes & flags != flags is equivalent to initRes & (flags != flags) which will always be false. You need to use (initRes & flags) != flags instead.

Jpeg support is an optional feature, you need to enable libjpeg-turbo.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60