Picture file is a fixed format, like BMP Picture: file header + bitmap color data.
The file header is typically read using the following code:
Bitmapfileheader fileheader={0}; Fread (&fileheader,sizeof(Fileheader),1, FP); if(fileheader.bftype!=0x4d42)//determine if BMP is a picture{fclose (FP); return ; } Bitmapinfoheader head; Fread (&head,sizeof(Bitmapinfoheader),1, FP); LongBmpwidth = Head.biwidth;//get the width of the picture LongBmpheight = Head.biheight;//get the width of the pictureWORD biBitCount =Head.bibitcount; if(biBitCount! = -)//whether it is a 24-bit bitmap{:: AfxMessageBox (_t ("Please select a 24-bit bitmap! ")); Fclose (FP); return ; }
The file is read here to read the color data of the bitmap, then before reading, we need to know the size of the data, so as to assign the specific university buffer, and then the complete reading of the data into the buffer.
Then calculate the size of the bitmap data is generally done with the following code.
int totalsize = (bmpwidth *bibitcount/8+3)/4*4*New Byte[totalsize];
After the work is done, we use the fread command to read the contents of the file directly until the end of the file is read.
The entire specific code is implemented as follows
FILE *fp=NULL; intret = fopen_s (&FP,"d:\\11.bmp","RB"); if(fp==0) { return ; } bitmapfileheader Fileheader={0}; Fread (&fileheader,sizeof(Fileheader),1, FP); if(fileheader.bftype!=0x4d42) {fclose (FP); return ; } Bitmapinfoheader head; Fread (&head,sizeof(Bitmapinfoheader),1, FP); LongBmpwidth =Head.biwidth; LongBmpheight =Head.biheight; WORD biBitCount=Head.bibitcount; if(biBitCount! = -) {:: AfxMessageBox (_t ("Please select a 24-bit bitmap! ")); Fclose (FP); return ; } intTotalSize = (Bmpwidth *bibitcount/8+3)/4*4*Bmpheight; BYTE*pbmpbuf =NewByte[totalsize]; size_t size=0; while(true) { intIret = Fread (&pbmpbuf[size],1,1, FP); if(Iret = =0) Break; Size= size +Iret; } fclose (FP); inti,j; CCLIENTDC DC ( This); intpitch=bmpwidth%4; for(i=0; i<bmpheight;i++) { intrealpitch=i*pitch; for(j=0; j<bmpwidth;j++) {DC. SetPixel (J,i,rgb (pbmpbuf[(i*BMPWIDTH+J) *3+2+Realpitch], pbmpbuf[(i*BMPWIDTH+J) *3+1+Realpitch], pbmpbuf[(i*BMPWIDTH+J) *3+Realpitch])); }} Delete [] pbmpbuf; Pbmpbuf=NULL; return;
C + + method for reading BMP bitmap data