reading TGA files in OpenGl to create a 3d ouse

571 views Asked by At

I have a TGA file and a library that allready has everything that I need to read TGA and use them.

This class has a method called pixels(), that returns a pointer that is pointed to the memory area where pixel are stored as RGBRGBRGB...

My question is, how can I take the pixel value?

Cause if I make something like this:

img.load("foo.tga");
printf ("%i", img.pixels());

It gives back to me what is proprably the address.

I've found this code on this site:

struct Pixel2d
{
    static const int SIZE = 50;
    unsigned char& operator()( int nCol,  int nRow, int RGB)
    {
        return pixels[ ( nCol* SIZE + nRow) * 3 + RGB];
    }

    unsigned char pixels[SIZE * SIZE * 3 ];
};

int main()
{

    Pixel2d p2darray;
    glReadPixels(50,50, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &p.pixels);

    for( int i = 0; i < Pixel2d::SIZE ; ++i )
    {
        for( int j = 0; j < Pixel2d::SIZE ; ++j )
        {
            unsigned char rpixel = p2darray(i , j , 0);
            unsigned char gpixel = p2darray(i , j , 1);
            unsigned char bpixel = p2darray(i , j , 2);
        }
    }
}

I think that It can work great for me, but how can I tell the program to read from my img?

1

There are 1 answers

2
Rafael Baptista On

Tga supports different pixel depths. And we don't know what library you're using. But generally speaking pixels() should return a pointer to a buffer containing pixels. Say for sake of argument it unpacks the pixels into 8-bit per channel subpixels, then each pixel is represented by 3 bytes.

So to access a pixel at a given offset in the buffer:

const u8* pixelBuffer = img.pixels():

u8 red   = pixelBuffer[(offset*3)+0];
u8 green = pixelBuffer[(offset*3)+1];
u8 blue  = pixelBuffer[(offset*3)+2];

If you know the width of the image buffer then you can get a pixel by its x and y coordinates:

u8 red = pixelBuffer[((x+(y*width))*3)+0];