在OpenGl中读取TGA文件以创建一个3d房屋

时间:2012-10-23 14:59:17

标签: c++ opengl textures tga

我有一个TGA文件和一个库已经拥有我需要读取TGA并使用它们的所有内容。

这个类有一个名为pixels()的方法,它返回一个指向存储区域的指针,其中像素存储为RGBRGBRGB ......

我的问题是,如何获取像素值?

因为我做了这样的事情:

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

它回复了我可信的地址。

我在这个网站上找到了这段代码:

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);
        }
    }
}

我认为它对我来说很有用,但我如何告诉程序从我的img中读取?

1 个答案:

答案 0 :(得分:1)

Tga支持不同的像素深度。我们不知道您正在使用哪个库。但一般来说,pixels()应返回指向包含像素的缓冲区的指针。为了论证起见,它将像素解包为每通道8位子像素,然后每个像素用3个字节表示。

所以要访问缓冲区中给定偏移量的像素:

const u8* pixelBuffer = img.pixels():

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

如果你知道图像缓冲区的宽度,那么你可以通过x和y坐标获得一个像素:

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