Skip to main content
gamedev.net
🔒 Locked

Function to load PNG

Started by silverphyre673 Mar 16, 2005 at 12:35 AM 3 replies 850+ views
Original Post
silverphyre673
silverphyre673
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;
} TEXTURE_IMAGE;

typedef TEXTURE_IMAGE * P_TEXTURE_IMAGE;

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)
            {
                fin.get(c);
                *p = c;
            }
        }
    }
    fin.close();
    return true;
}

my siteGenius is 1% inspiration and 99% perspiration
Telastyn
Telastyn
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.
Cygon
Cygon
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 pixelsdelete pImage;


-Markus-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.