加载bmp文件为纹理也是比较常用的了。
unsigned char *CTestDemoDlg::loadBMP(char *filename, BITMAPINFOHEADER *bmpInfo)
{
FILE *file;
BITMAPFILEHEADER bmpFile;
unsigned char *bmpImage = NULL;
unsigned char tmpRGB;
file = fopen(filename,"rb");
if (!file)
{
::MessageBox(NULL, "Can't Find Bitmap", "Error", MB_OK);
return NULL;
}
fread(&bmpFile,sizeof(BITMAPFILEHEADER),1,file);
if (bmpFile.bfType != 0x4D42)
{
::MessageBox(NULL, "Incorrect texture type", "Error", MB_OK);
fclose(file);
return NULL;
}
fread(bmpInfo,sizeof(BITMAPINFOHEADER),1,file);
fseek(file,bmpFile.bfOffBits,SEEK_SET);
bmpImage = new unsigned char[bmpInfo->biSizeImage];
if (!bmpImage)
{
::MessageBox(NULL, "Out of Memory", "Error", MB_OK);
delete[] bmpImage;
fclose(file);
return NULL;
}
fread(bmpImage,1,bmpInfo->biSizeImage,file);
if (!bmpImage)
{
::MessageBox(NULL, "Error reading bitmap", "Error", MB_OK);
fclose(file);
return NULL;
}
for (unsigned int i = 0; i < bmpInfo->biSizeImage; i+=3)
{
tmpRGB = bmpImage[i];
bmpImage[i] = bmpImage[i+2];
bmpImage[i+2] = tmpRGB;
}
fclose(file);
return bmpImage;
}
BOOL CTestDemoDlg::LoadTexture(char *filename, GLuint *id)
{
BITMAPINFOHEADER info;
unsigned char *bitmap;
bitmap = loadBMP(filename, &info);
if (!bitmap)
return false;
glGenTextures(1, id);
glBindTexture(GL_TEXTURE_2D, *id);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, info.biWidth, info.biHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, bitmap);
return TRUE;
}
使用格式:LoadTexture("Data/Compressed.bmp", &m_Texture);