#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <iostream>
#pragma pack(2)
using namespace std;
typedef struct BITMAPFILEHEADER
{
u_int16_t bfType;
u_int32_t bfSize;
u_int16_t bfReserved1;
u_int16_t bfReserved2;
u_int32_t bfOffBits;
}BITMAPFILEHEADER;
typedef struct BITMAPINFOHEADER
{
u_int32_t biSize;
u_int32_t biWidth;
u_int32_t biHeight;
u_int16_t biPlanes;
u_int16_t biBitCount;
u_int32_t biCompression;
u_int32_t biSizeImage;
u_int32_t biXPelsPerMeter;
u_int32_t biYPelsPerMeter;
u_int32_t biClrUsed;
u_int32_t biClrImportant;
}BITMAPINFODEADER;
int main()
{
FILE *fpBmp;
BITMAPFILEHEADER bmpHeader;//包含文件类型、大小和布局的信息
BITMAPINFOHEADER bmpInfHeader;//包含位图的尺寸和颜色格式
const char *bmpname = "/usr/workspace/grid_map.bmp";
const char *txtname = "/usr/workspace/area_map.txt";
if((fpBmp = fopen(bmpname,"rb"))==NULL)
{
cout<<"the bmp file can not open!"<<endl;
return 0;
}
//read the BITMAPFILEHEADER
fread(&bmpHeader,sizeof(BITMAPFILEHEADER),1,fpBmp);
//read the BITMAPINFOHEADER
fread(&bmpInfHeader,sizeof(BITMAPINFOHEADER),1,fpBmp);
// read bmp data
unsigned char *bmpData = new unsigned char[bmpInfHeader.biHeight*bmpInfHeader.biWidth*3];
//unsigned char *bmpData = new unsigned char[bmpInfHeader.biHeight * bmpInfHeader.biWidth];//黑白图像
fseek(fpBmp,bmpHeader.bfOffBits,SEEK_SET);
fread(bmpData,1,bmpInfHeader.biHeight*bmpInfHeader.biWidth*3,fpBmp);
//fread(bmpData,1,bmpInfHeader.biHeight * bmpInfHeader.biWidth,fpBmp);//黑白图像
FILE *temp;
if((temp = fopen(txtname,"wb"))==NULL)//写TXT文件
{
cout<<"the file can not be built!"<<endl;
return 0;
}
// fprintf(temp,"0 0 ");
fprintf(temp,"%d ",bmpInfHeader.biHeight);
fprintf(temp,"%d\n",bmpInfHeader.biWidth);
for(int i = 0;i<bmpInfHeader.biHeight;i++)
{
for(int j = 0;j<bmpInfHeader.biWidth;j++)
{
fprintf(temp,"%d ",bmpData[i*bmpInfHeader.biWidth*3 + j*3]);
fprintf(temp,"%d ",bmpData[i*bmpInfHeader.biWidth*3 + j*3+1]);
fprintf(temp,"%d ",bmpData[i*bmpInfHeader.biWidth*3 + j*3+2]);
//fprintf(temp,"%d ",bmpData[i*bmpInfHeader.biWidth + j]);//黑白图像
}
fprintf(temp,"\n");
}
fclose(fpBmp);
fclose(temp);
return 0;
}
可以解析黑白图和彩色图,并将像素信息写进txt文件。