学完本课后自己也试着写了个,哈哈,好使
#include <stdlib.h>
#include <iostream.h>
#include <stdio.h>
#include <gl/glut.h>
#include <gl/gl.h>
GLvoid* pPD;
GLint ImgW,ImgH;
//函数功能:加载24bit位图(*.bmp)到内存
// 参数:文件名 || 返回的图像宽 || 返回的图像高 || 返回的错误类型
// Err:(1:打开文件错误 | 2:文件类型错误 | 3:分配内存错误 | 4:文件长度不足或文件类型错误)
// 返回值:内存指针 || NULL
GLvoid* k_LoadBmp(const char* FileName,GLint* ImageWidth,GLint* ImageHeight,int* Err)
{
GLint TempInt;
GLuint PixelLength;
GLbyte TempByte;
GLvoid* pPixelData;
FILE* pFile;
pFile=fopen(FileName, "rb");
if(!pFile)
{
*Err = 1;
return NULL;
}
//_______________check bmp file
fseek(pFile, 0x0000, SEEK_SET);
fread(&TempByte, 1, 1, pFile);
if (TempByte != 'B')
{
*Err = 2;
fclose(pFile);
return NULL;
}
fread(&TempByte, 1, 1, pFile);
if (TempByte != 'M')
{
*Err = 2;
fclose(pFile);
return NULL;
}
fseek(pFile, 0x000a, SEEK_SET);
fread(&TempInt, 4, 1, pFile);
if (TempInt != 0x0036)
{
*Err = 2;
fclose(pFile);
return NULL;
}
fseek(pFile, 0x001c, SEEK_SET);
fread(&TempInt, 4, 1, pFile);
if (TempInt != 0x0018)
{
*Err = 2;
fclose(pFile);
return NULL;
}
fseek(pFile, 0x0002, SEEK_SET);
fread(&TempInt, 4, 1, pFile);
fseek(pFile, 0x0022, SEEK_SET);
fread(&PixelLength, 4, 1, pFile);
if (TempInt - PixelLength != 0x0036)
{
*Err = 2;
fclose(pFile);
return NULL;
}
//_______________check bmp file
//_______________read pixeldata
fseek(pFile, 0x0012, SEEK_SET);
fread(ImageWidth, 4, 1, pFile);
fread(ImageHeight, 4, 1, pFile);
pPixelData =(GLvoid*)malloc(PixelLength);
if(pPixelData == NULL)
{
*Err = 3;
fclose(pFile);
return NULL;
}
fseek(pFile, 0x0036, SEEK_SET);
if(fread(pPixelData, 1, PixelLength, pFile) != PixelLength)
{
*Err = 4;
fclose(pFile);
return NULL;
}
fclose(pFile);
//_______________read pixeldata
*Err = 0;
return pPixelData;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glDrawPixels(ImgW, ImgH, GL_BGR_EXT, GL_UNSIGNED_BYTE, pPD);
glutSwapBuffers();
}
int main(int argc, char **argv)
{
int err;
pPD=k_LoadBmp("d:\\a.bmp", &ImgW, &ImgH, &err);
if(!pPD)
{
cout<<err<<endl;
return 0;
}
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE| GLUT_RGBA);
glutInitWindowSize (700, 700);
glutInitWindowPosition(10,10);
glutCreateWindow ("kapig");
glutDisplayFunc (display);
glutMainLoop();
return 0;
}
最后修改于2008-2-23 16:11:00