BMP全称bitmap(位图),是windows中的标准图像文件格式,可以读入一张bmp图像作为纹理.
以下是我目前正在使用的位图加载类.首先是头文件:
#define swapcolor(a,b){ (a) ^= (b); (b) ^= (a); (a) ^= (b); }
class BmpLoader {
private:
unsigned char* header;//文件头
unsigned int dataPos;//读取位置
unsigned int width, height;//图片宽度 高度
unsigned int imageSize;//图片内容大小
public:
unsigned char * data;//图片内容 rgb
BmpLoader();
~BmpLoader();
void bFree();
int getWidth();
int getHeight();
bool loadBitmap(const char* fileName);
};BmpLoader::BmpLoader() {
header=new unsigned char[54];
}
BmpLoader::~BmpLoader() {
bFree();
delete[] data;
}
void BmpLoader::bFree() {
delete[] header;
}
接着是读取图片的主要方法,fileName是图片名字(带路径)
bool BmpLoader::loadBitmap(const char* fileName) {
FILE * file = fopen(fileName,"rb");
if (!file) {
printf("Image could not be opened");
return false;
}
if (fread(header, 1, 54, file)!=54) {//文件头并非54字节 读取失败
printf("Not a correct BMP file");
return false;
}
if (header[0]!='B' || header[1]!='M') {//文件头开头并非BM 读取失败
printf("Not a correct BMP file");
return false;
}
dataPos = *(int*)&(header[0x0A]);//读取位置 位置在文件头0x0A处
imageSize = *(int*)&(header[0x22]);//图片内容大小数据 位置在文件头0x22处
width = *(int*)&(header[0x12]);//图片宽度数据 位置在文件头0x12处
height = *(int*)&(header[0x16]);//图片高度数据 位置在文件头0x16处
if (imageSize==0)
imageSize=width*height*3;//图片内容数据=总像素数x3(简单起见使用宽高为2的n次方大小的图片,不考虑4字节对齐)
if (dataPos==0)
dataPos=54;//文件头读完 位置在54字节处
data = new unsigned char [imageSize];//data放像素信息
fread(data,1,imageSize,file);//读取像素
fclose(file);
for(int i= 0;i<(int)imageSize;i+=3)
swapcolor(data[i],data[i+2]);//bgr变为rgb
return true;
}int BmpLoader::getWidth() {
return width;
}
int BmpLoader::getHeight() {
return height;
}
参考: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/

原文:http://blog.csdn.net/zxx43/article/details/41594871