简体   繁体   English

读取BMP文件会返回意外数据

[英]Reading BMP file gives back unexpected data

I made a bitmap with the following first row: 0000000000000000000000000000000111111111 (It's a black line on the edge of the bitmap) But when I read the bitmap I get back the following data on the first row: 1000100100001001000010010000100100001001 我用下面的第一行制作了一个位图:0000000000000000000000000000000000000111111111(这是位图边缘上的黑线)但是当我读取位图时,我在第一行上得到了以下数据:1000100100001001000010010000100100001001

Actually the first 3 rows contain the 1's and some zeros. 实际上,前3行包含1和一些零。 The rest of the values are 0's. 其余值为0。 I use the following code: 我使用以下代码:

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

int main() {
    FILE* f = fopen("C:\\Users\\Laptop_Chris\\Documents\\kleinObject.bmp", "rb");
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, f);

    int size = ((*(int*)&info[18] * 3 + 3) & (~3)) * *(int*)&info[22]; //BMP - HEIGHT: *(int*)&info[22]  -  WIDTH:*(int*)&info[18]

    unsigned char* data = new unsigned char[size];
    fread(data, sizeof(unsigned char), size, f);
    fclose(f);

    vector< vector<bool> > myVector;
    myVector.resize(*(int*)&info[22], vector<bool>(*(int*)&info[18]));

    int i = 0;

    for (auto a = 0; a < *(int*)&info[22]; a++) {
        for (auto q = 0; q < *(int*)&info[18]; q++) {
            if ((int(data[i] & 0xFF) + int(data[i + 1] & 0xFF) + int(data[i + 2] & 0xFF)) > 0) {
                myVector[a][q] = false;
            }
            else {
                myVector[a][q] = true;
            }
            i = i + 3;
            cout << myVector[a][q];
        }
        cout << endl;
    }
    cin.get();
    return 0;
}

Anybody that understands this behavior? 有人了解这种行为吗? Thanks in advance. 提前致谢。

Your assumptions are that you have a RGB24 bitmap and that BITMAPINFOHEADER::biHeight > 0 (that is your *(int*)&info[22] ). 您的假设是您具有RGB24位图,并且BITMAPINFOHEADER :: biHeight> 0(即您的*(int*)&info[22] )。 Note that this means that your image is stored from bottom row to top row. 请注意,这意味着您的图像是从底行到顶行存储的。

Furthermore, you handle 4 byte padding when computing size , but you are not handling it when reading out data . 此外,在计算size时可以处理4个字节的填充,但是在读取data时不进行处理。

Also note that you are outtputting 1 for R=G=B=0 (ie black) and 0 otherwise. 还要注意,对于R = G = B = 0(即黑色),您的输出为1,否则为0。 You probably intend the opposite. 您可能打算相反。

You should also add a delete [] data; 您还应该添加一个delete [] data; at the end. 在末尾。

Summary: your code only works for an RGB24 image with biHeight > 0 and (3 * biWidth) % 4 == 0 and you have to be aware that you are outputting from bottom row to top row and 1 for R=G=B=0 and 0 otherwise. 摘要:您的代码仅适用于biHeight> 0和(3 * biWidth)%4 == 0的RGB24图像,并且必须注意,您是从底部到顶部输出,对于R = G = B =为1。 0,否则为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM