读取bmp

参考这篇文章的讲解bitmap格式http://blog.csdn.net/pathuang68/article/details/4219681

我试了下,用了个bicount=24的bmp,最后读到一个二维数组打算用setpixel输出时发现显示不正确

去stackoverflow上问了下,得到了解答,bitmap每一row会对32bit对齐,

所有每行末尾可能有padding data,用

int rowbyte=(pixelbyte*width+3)&~3;

int skipdata=rowbyte-pixelbyte*width;(这个好聪明的算法...)

得出skipdata,末尾时跳过即可。

同时rgb在内存中存储的顺

 1 #include<iostream>
 2 #include<fstream>
 3 #include<windows.h>
 4 
 5 
 6 using namespace std;
 7 
 8 struct BITMAPHEADER
 9 {
10     unsigned short btType;
11     unsigned int bfSize;
12     unsigned short bfReserved1;
13     unsigned short bfReserved2;
14     unsigned int bfoffBits;
15 };
16 
17 //struct BITMAPINFOHEADER
18 //{
19 //    unsigned int biSize;
20 //    unsigned int biWith;
21 //    unsigned int biHeight;
22 //    unsigned short biPlanes;
23 //    unsigned short biBitCount;
24 //    unsigned int biCompression;
25 //    unsigned int biSizeImage;
26 //    unsigned int biXPelsPerMeter;
27 //    unsigned int biYPerlPerMeter;
28 //    unsigned int biClrused;
29 //    unsigned int biClrImportant;
30 //};
31 //
32 //struct RGBQUAD
33 //{
34 //    char rgbBlue;
35 //    char rgbGreen;
36 //    char rgbRed;
37 //    char rgbReserved;
38 //
39 //};
40 int main()
41 {
42     tagBITMAPFILEHEADER bh;
43     BITMAPINFOHEADER bih;
44     char buf[3];
45     unsigned char bmp[200][600];
46     int width ,height;
47     ifstream fin(L"D:\美图图库\3.bmp",ios::_Nocreate|ios::binary);
48     fin.read((char*)&bh,sizeof(bh));
49     fin.read((char*)&bih,sizeof(bih));
50     
51 
52     width=bih.biWidth;
53     height=bih.biHeight;
54     HWND myconsole=GetConsoleWindow();
55     HDC mydc=GetDC(myconsole);
56     int rowdata=(width*3+3)&~3;
57     int skipdata=rowdata-width*3;
58     char skip[4];
59     for(int i=height;i>=1;i--)
60     {
61         for(int j=1;j<=width;j++)
62         {
63             fin.read(buf,sizeof(buf));
64             bmp[i][j*3]=buf[0];
65             bmp[i][j*3+1]=buf[1];
66             bmp[i][j*3+2]=buf[2];
67         
68         }
69         fin.read(skip,skipdata);
70     }
71         for(int i=1;i<=height;i++)
72         {
73             for(int j=1;j<=width;j++)
74             {
75 
76                 COLORREF color;
77                 color=RGB(bmp[i][j*3+2],bmp[i][j*3+1],bmp[i][j*3]);
78                 SetPixel(mydc,j,i,color);
79             }
80     
81         }
82         ReleaseDC(myconsole,mydc);
83     fin.close();
84     return 0;
85 }

序从低到高是B G R的顺序,所有最后要反过来一下。

原文地址:https://www.cnblogs.com/cavehubiao/p/3421595.html