如何读写BMP文件中的图象像素数据
发布网友
发布时间:2022-05-02 23:16
我来回答
共1个回答
热心网友
时间:2022-06-28 06:10
BMP图像像素读取的另一种方法
功能:读取BMP图像,将其像素值存储在TXT文档中。
#include <iostream>
#include <windows.h>
#include <stdlib.h>
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!"<<endl;
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!"<<endl;
exit(1);
}
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 \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;
}