Jump to content
  • Advertisement
Sign in to follow this  

Function to load PNG

This topic is 4994 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I kind of adapted one of NeHe's tutorials that teaches how to load RAW images, because I need a function to load images with an alpha channel. I'm not sure how PNGs are stored, or where to look, so I would be VERY appreciative if you could look at this source and tell me if I'm on the right track... Thanks!
typedef struct tagTEXTURE_IMAGE
    int width;
    int height;
    int format;
    unsigned char* data;


bool LoadPNG(const char * filename, P_TEXTURE_IMAGE buffer)
    int width = buffer->width;
    int height = buffer->height;
    int format = buffer->format;
    ifstream fin(filename, ifstream::binary);
    int stride = width * format;
    unsigned char* p=NULL;
    char c;
    int done=0;
    if (!fin)
        return false;
    //We have successfully loaded into 'fin'
    for (unsigned i=0; i<height; ++i)
        p = buffer->data + (i * stride);
        for (unsigned j=0; j<width; ++j)
            for (unsigned k=0; k<format; ++k, ++p, ++done)
                *p = c;
    return true;

Share this post

Link to post
Share on other sites
If you're using DirectX, some of the helper functions will load pngs for you. D3DXCreateTextureFromFile and it's ilk. Thats what I use, and that alone was enough to prompt me to learn DX9 rather than DDraw despite the fewer tutorials.

Share this post

Link to post
Share on other sites
Corona uses libpng, the official reference library for loading png files.

But instead of wasting time with libpng, I'd recommend you to just use Corona directly. It's far easier than writing your own functions for all those file formats and you'll get bmp, pcx, jpeg and more for free.

It's actually very easy to use corona for loading an image:

corona::Image *pImage = corona::OpenImage("my_image.png", corona::PF_R8G8B8A8);

// Do something with the loaded image
// pImage->getPixels() returns a pointer to the pixel data
// pImage->getWidth() is the image's width in pixels
// pImage->getHeight() is the image's height in pixels

delete pImage;


Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!