nothings / stb

stb single-file public domain libraries for C/C++
https://twitter.com/nothings
Other
26.84k stars 7.72k forks source link

stb_image loader fails on anything but PNG #1317

Closed pdm-pcb closed 2 years ago

pdm-pcb commented 2 years ago

Greets, all. Thanks for underpinning my gamedev ambitions for years and years. =)

I recently tried loading a JPEG file (specifically, some of these) and much to my chagrin, the image loader would bail out, insisting that what I was trying to load was not a PNG. Of course, it was correct in this assertion, but surely that's no reason to fail? Haha.

Anyway, I stepped through and noticed that while the image was being loaded properly, stbi__g_failure_reason was not being cleared out after stbi__png_test() populated it. So I just tacked on this line:

    // test the formats with a very explicit header first (at least a FOURCC
    // or distinctive magic number first)
#ifndef STBI_NO_PNG
    if(stbi__png_test(s))  return stbi__png_load(s, x, y, comp, req_comp, ri);
    else stbi__g_failure_reason = NULL;
#endif

and it seemed to solve my issue. I also added that NULL assignment as an else for every image type test, and it seems to not have exploded. I'm not at all claiming this is a fix, but it produced the desired behavior in my extremely narrow use case. And for what it's worth, I don't have anything defined in the implementation file aside from the requisite STB_IMAGE_IMPLEMENTATION. Pretty sure I'm doing it right?

It seems unlikely that a behavior like this just happened to slip through, but this is what I've got. Just figured I'd share. =)

nothings commented 2 years ago

stbi__g_failure_reaon has an undefined value if no error occurs. you have to check whether there was an error before looking at that value.

so, case 1, stbi_load is returning an error and you're getting a PNG message but it's not PNG, that's one case, and there's a bug in stb_image. case 2, you're not checking if stbi_load is returning an error and you're checking the failure message, that's a bug in your code. given the behavior you describe with your suggested change, it sounds like case 2.

pdm-pcb commented 2 years ago

Thank you very kindly for the guidance. =)