c++bmp到2d数组打印不切实际的值

c++ bmp to 2d-array prints unrealistic values

本文关键字:不切实际 打印 数组 2d c++bmp      更新时间:2023-10-16


我正在做一个小项目,遇到了麻烦。我必须将bmp文件转换为Color的2d数组(我为每种颜色制作了自己的typedef结构(。代码工作正常(没有遇到任何错误(,一些值与图像匹配,但其他值不匹配;我的图像的前三个像素都是白色的,而他说它们首先是红色,然后是绿色,最后是蓝色。

#include <string>
#include <iostream>
#include <fstream>
using namespace std;
const int W = 960, H = 720;
typedef struct Colors {
    int red;
    int green;
    int blue;
} Color;

Color image[H][W];
void readBMP(char *filename) {
    FILE *f = fopen(filename, "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header
    // extract image height and width from header
    int width = *(int *) &info[18];
    int height = *(int *) &info[22];
    /* W = width;
    H = height;*/
    int size = 3 * width * height;
    unsigned char *data = new unsigned char[size]; // allocate 3 bytes per pixel
    fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
    fclose(f);
    int index = 0;
    for (int j = 0; j < H; j++) {
        //cout << index << endl;
        for (int k = 0; k < W; k++) {
            index = (j * W) * 3 + k * 3;
            Color c;
            c.blue = (int) data[index];
            c.green = (int) data[index + 1];
            c.red = (int) data[index + 2];
            //cout << "j/width: " << (j / width) << endl << "j%width: " << (j % width) << endl << endl;
            image[j][k] = c;
            cout << (image[j][k]).red << ' ' << (image[j][k]).green << ' '     << (image[j][k]).blue << endl;
        }
    }
}
int main() {
    //std::cout << "this is a test function" << endl;
    readBMP((char *) "test.bmp");
}

前50行的输出为:

255 0 0
255 0 0
255 0 0
0 0 0
0 0 0
71 66 255
128 115 82
40 245 194
30 184 96
133 32 21
64 1 235
19 51 51
102 102 128
102 64 38
160 6 102
9 153 153
215 10 60
92 36 3
0 50 143
0 0 0
0 0 0
0 0 0
4 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
107 152 191
105 150 189
104 149 188
105 150 189
104 149 188
100 145 184
97 141 180
96 140 179
96 138 176
96 138 176
98 137 176
99 138 177
101 140 179
103 142 181
106 144 183
106 145 184
111 150 189
106 148 186
107 149 187
105 147 185
104 143 182
112 151 190
...

提前感谢,Jari

这不是一个完整的位图解析器,它只能读取24位位图。它不检查或读取位域位图,也不读取基于混叠的位图。

最重要的是,这可能是正在发生的事情。每次读取颜色时,32位位图将导致通道移动到下一个通道。这意味着大多数颜色在某种程度上是不正确的。

你必须检查标题中每个像素的比特数——它是第15位的uint16_t;标头中的第16个字节。

但是要注意,这个解析器还有很多其他问题。