原文地址:点击打开链接
读取BMP文件的时候我们首先需要弄清楚bmp格式文件的结构
bmp的文件格式
bmp文件包含在windows.h的头文件里。编写代码的时候可以直接调用Windows.h 头文件来调用。
实现代码
#include<iostream>#include<windows.h>#include<fstream>#include<cstdlib>#include<cstdio>#include<cmath>#include<iomanip>using namespace std;unsigned char *pBmpBuf;int bmpWidth;int bmpHeight;RGBQUAD *pColorTable;int biBitCount;bool readBmp(char *bmpName) { FILE *fp=fopen(bmpName,"rb"); if(fp==0) return 0; fseek(fp, sizeof(BITMAPFILEHEADER),0); BITMAPINFOHEADER head; fread(&head, sizeof(BITMAPINFOHEADER), 1,fp); bmpWidth = head.biWidth; bmpHeight = head.biHeight; biBitCount = head.biBitCount; int lineByte=(bmpWidth * biBitCount/8+3)/4*4; if(biBitCount==8) { pColorTable=new RGBQUAD[256]; fread(pColorTable,sizeof(RGBQUAD),256,fp); } pBmpBuf=new unsigned char[lineByte * bmpHeight]; fread(pBmpBuf,1,lineByte * bmpHeight,fp); fclose(fp); return 1;}bool saveBmp(char *bmpName, unsigned char *imgBuf, int width, int height, int biBitCount, RGBQUAD *pColorTable){ if(!imgBuf) return 0; int colorTablesize=0; if(biBitCount==8) colorTablesize=1024; int lineByte=(width * biBitCount/8+3)/4*4; FILE *fp=fopen(bmpName,"wb"); if(fp==0) return 0; BITMAPFILEHEADER fileHead; fileHead.bfType = 0x4D42; fileHead.bfSize= sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTablesize + lineByte*height; fileHead.bfReserved1 = 0; fileHead.bfReserved2 = 0; fileHead.bfOffBits=54+colorTablesize; fwrite(&fileHead, sizeof(BITMAPFILEHEADER),1, fp); BITMAPINFOHEADER head; head.biBitCount=biBitCount; head.biClrImportant=0; head.biClrUsed=0; head.biCompression=0; head.biHeight=height; head.biPlanes=1; head.biSize=40; head.biSizeImage=lineByte*height; head.biWidth=width; head.biXPelsPerMeter=0; head.biYPelsPerMeter=0; fwrite(&head, sizeof(BITMAPINFOHEADER),1, fp); if(biBitCount==8) fwrite(pColorTable, sizeof(RGBQUAD),256, fp); fwrite(imgBuf, height*lineByte, 1, fp); fclose(fp); return 1;} void doIt(){ char readPath[]="girl.bmp"; readBmp(readPath); cout << "width=" << bmpWidth << "height=" << bmpHeight << "biBitCount=" << biBitCount <<endl; int linebyte1=(bmpWidth*biBitCount/8+3)/4*4; int n =0,m=0,count_xiang_su = 0; if(biBitCount == 8) { for(int i=0;i<bmpHeight/2;i++) { for(int j=0;j<bmpWidth/2;i++) *(pBmpBuf+i*linebyte1+j)=0; } } if(biBitCount == 24) { for(int i=0;i<bmpHeight;i++) { for(int j=0;j<bmpWidth;j++) { for(int k=0;k<3;k++) { m= *(pBmpBuf+i*linebyte1+j*3+k); count_xiang_su++; } n++; } } cout<<"总的像素个素为:"<<n<<endl; cout<<"----------------------------------------------------"<<endl; } char writePath[] = "necpy.BMP"; saveBmp(writePath, pBmpBuf, bmpWidth, bmpHeight, biBitCount, pColorTable); delete []pBmpBuf; if(biBitCount==8) delete []pColorTable; }int main(){ doIt(); system("pause"); return 0;}