Mac下Opengl读取tga纹理(蓝宝书readtga函数不能用)

话不多说,直接上函数

GLbyte *ReadTGABits(const char *szFileName, GLint *iWidth, GLint *iHeight, GLint *iComponents, GLenum *eFormat);
bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
    GLbyte *pBits;
    int nWidth, nHeight, nComponents;
    GLenum eFormat;

    pBits = ReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
    if(pBits == NULL)
        return false;

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, nComponents, nWidth, nHeight, 0,
                 eFormat, GL_UNSIGNED_BYTE, pBits);

    free(pBits);

    if(minFilter == GL_LINEAR_MIPMAP_LINEAR ||
       minFilter == GL_LINEAR_MIPMAP_NEAREST ||
       minFilter == GL_NEAREST_MIPMAP_LINEAR ||
       minFilter == GL_NEAREST_MIPMAP_NEAREST)
        glGenerateMipmap(GL_TEXTURE_2D);

    return true;
}
GLbyte *ReadTGABits(const char *szFileName, GLint *iWidth, GLint *iHeight, GLint *iComponents, GLenum *eFormat)
{
    FILE *pFile;

    typedef struct
    {
       GLubyte Header[12];

        GLubyte header[6];
    }TGAHEADER;

    unsigned long lImageSize;
    GLuint sDepth;
    GLbyte *pBits=NULL;

    TGAHEADER tgaHeader;


    *iWidth=0;
    *iHeight=0;
    *eFormat=GL_RGB;
    *iComponents=GL_RGB;

    pFile=fopen(szFileName,"rb");
    if(pFile==NULL)
        return NULL;
    fread(&tgaHeader,18,1,pFile);

    *iWidth=tgaHeader.header[1]*256+tgaHeader.header[0];
    *iHeight=tgaHeader.header[3]*256+tgaHeader.header[2];
    sDepth=tgaHeader.header[4]/8;

//    cout<<"1="<<*iWidth<<endl;
//    cout<<"2="<<*iHeight<<endl;
//    cout<<"3="<<sDepth;

    if(tgaHeader.header[4]!=8&&tgaHeader.header[4]!=24&&tgaHeader.header[4]!=32)
        return NULL;
    lImageSize=(*iWidth)*(*iHeight)*sDepth;

    pBits=(GLbyte*)malloc(lImageSize*sizeof(GLbyte));
    if(pBits==NULL)
        return NULL;
    if(fread(pBits,lImageSize,1,pFile)!=1)
    {
        free(pBits);
        return NULL;
    }
    switch(sDepth)
    {
        case 4:
            *eFormat=GL_BGRA;
            *iComponents=GL_RGBA;
            break;
        case 1:
            *eFormat=GL_LUMINANCE;
            *iComponents=GL_LUMINANCE;
            break;
    }

    
    for(GLuint i=0;i<int(lImageSize);i+=sDepth)
    {
        GLubyte temp=pBits[i];
        pBits[i]=pBits[i+2];
        pBits[i+2]=temp;
        
    }
    fclose(pFile);
    
    return pBits;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值