0
\$\begingroup\$

PNG loading:

I've been creating a game engine for almost a year, and since the start of the development, I have been using stb_image for loading images. It relatively lightweight but has lots of functionallity I don't personally need. I want to keep the engine as simple and lightweight as possible, so I was hoping how to load pngs from a file directly, in pure C. I made some research and all the people was asking for was about loading BMP or TGA, but no one was asking about PNG loading, and if someone asked it, people will always recommend a third party library.

What I mean:

#define RGB 0
#define RGBA 1
// more loading types...

unsigned char* load_image(const char* filename, int* width, int* height, int* channels, int mode) {
    
    unsigned char* data = NULL;

    FILE* fp = fopen(filename, "rb");
    assert(fp);
    
    /*
     * Magic to read 'fp' and get the raw bytes,
     * the width, the height and the channels
     */
    return data;
}

How could I read the whole file, and then, return the raw bytes of the image (for OpenGL, to create textures), the width and the height as well as the image channels? Also, how could I implement a: "loading mode selector", for choosing between RGBA mode or RGB or even more modes?

\$\endgroup\$
  • 7
    \$\begingroup\$ You have access to the source code of of the image loader, can't you just read it and reuse the code? \$\endgroup\$ – Vaillancourt Sep 3 at 0:49
  • 1
    \$\begingroup\$ The reason why libraries are recommended for PNG loading is because it's significantly more complex than BMP or TGA. It's a compressed file format so there are no raw bytes you can supply to glTexImage. You can read the source code of stb_image or libpng to see this for yourself. \$\endgroup\$ – Maximus Minimus Sep 3 at 7:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.