Search code examples
c++imagejpeg

Stb Image not loading in data correctly


Im using the stb_image.h library and my goal is to get the rgb data for each of the pixels of a jpg. But when I call the load function, it only gives me a bunch of weird symbols and not actual numbers. Could this be due to the image or is my code just wrong?

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

#include <iostream>
#include <string>

using namespace std;
int main()
{
    int width, height;
    int comp;
    const char* filename = "C:/Users/graha/source/repos/AiFirsy/Debug/rainbow.jpg";

    unsigned char* data = stbi_load(
        filename, &width, &height, &comp, 0);

    if (data == nullptr) {
        std::cerr << "ERROR: Could not load texture image file '" << filename << "'.\n";
        width = height = 0;
    }

    cout << data[0];

}

Heres the image

rainbow.jpg


Solution

  • The output stream (std::cout in this case) will interpret 'char' types as characters. If you want to see the numerical values, you can cast the values to an appropriate type. For example:

    unsigned char const value = 'c';
        
    std::cout << value << std::endl;
    std::cout << static_cast<unsigned int>(value) << std::endl;
    

    Outputs:

    c
    99
    

    Also, as an aside, you're accessing data even if it's null, which I'm guessing isn't what you want.