簡體   English   中英

讀取BMP文件會返回意外數據

[英]Reading BMP file gives back unexpected data

我用下面的第一行制作了一個位圖:0000000000000000000000000000000000000111111111(這是位圖邊緣上的黑線)但是當我讀取位圖時,我在第一行上得到了以下數據:1000100100001001000010010000100100001001

實際上,前3行包含1和一些零。 其余值為0。 我使用以下代碼:

#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;
}

有人了解這種行為嗎? 提前致謝。

您的假設是您具有RGB24位圖,並且BITMAPINFOHEADER :: biHeight> 0(即您的*(int*)&info[22] )。 請注意,這意味着您的圖像是從底行到頂行存儲的。

此外,在計算size時可以處理4個字節的填充,但是在讀取data時不進行處理。

還要注意,對於R = G = B = 0(即黑色),您的輸出為1,否則為0。 您可能打算相反。

您還應該添加一個delete [] data; 在末尾。

摘要:您的代碼僅適用於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