如何读写BMP文件中的图象像素数据

2020-10-21 教育 84阅读
BMP图像像素读取的另一种方法
功能:读取BMP图像,将其像素值存储在TXT文档中。
#include
#include
#include
using namespace std;
int main()
{
FILE *fpBmp;
BITMAPFILEHEADER bmpHeader;//包含文件类型、大小和布局的信息
BITMAPINFOHEADER bmpInfHeader;//包含位图的尺寸和颜色格式
const char *bmpname = "D://hzy124.bmp";
const char *txtname = "D://hzy124.txt";
if((fpBmp = fopen(bmpname,"rb"))==NULL)//fopen( "D://test.bmp","rb")
{
cout<<"the bmp file can not open!"<exit(1);
}
//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!"<exit(1);
}
for(int i = 0;i{
for(int j = 0;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 \t",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;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com