Cannot read BITMAPFILEHEADER of a bitmap file using C++ [duplicate]

二次信任 提交于 2020-01-11 11:27:09

问题


I am trying to read the FILEHEADER and INFOHEADER of a bitmap file, but I am unable to do so. I am getting Segmentation Fault.

My code has been given below.

#include <bits/stdc++.h>

using namespace std;

typedef int LONG;
typedef unsigned short WORD;
typedef unsigned int DWORD;

struct BITMAPFILEHEADER {
  WORD  bfType;
  DWORD bfSize;
  WORD  bfReserved1;
  WORD  bfReserved2;
  DWORD bfOffBits;
};

struct BITMAPINFOHEADER {
  DWORD biSize;
  LONG  biWidth;
  LONG  biHeight;
  WORD  biPlanes;
  WORD  biBitCount;
  DWORD biCompression;
  DWORD biSizeImage;
  LONG  biXPelsPerMeter;
  LONG  biYPelsPerMeter;
  DWORD biClrUsed;
  DWORD biClrImportant;
};

int main(void){
    ifstream file("lena.bmp");
    char* bf = NULL;
    int begin = file.tellg();
    file.seekg(0, ios::end);
    int end = file.tellg();
    int length = end-begin;

    file.read(bf, length);
    BITMAPFILEHEADER* file_header = (BITMAPFILEHEADER*)(bf);
    //BITMAPINFOHEADER* info_header = (BITMAPINFOHEADER*)(bf+sizeof(BITMAPFILEHEADER)-1);

    cout << file_header->bfSize << endl;
    //cout << info_header->biSize << endl;
    return 0;
}

回答1:


The segmentation fault is probably because you forgot to initialize bf;

int end = file.tellg();
int length = end-begin;
bf = new char[lenght+1]; //Add this
file.seekg(0, ios::beg); //And this too
file.read(bf, length);

[EDIT]

The second problem (size is always 0) occurs because the file pointer is at the end of the file, so you never read anything actually.




回答2:


As was mentioned in the previous reply, you where trying to file.read with a null pointer. I see that you are trying to load the whole file into memory, then do some pointer arithmetics to work with the data. But why not just read the BITMAPFILEHEADER directly instead?

ifstream file("lena.bmp");

// read in the header:
BITMAPFILEHEADER header;
file.read(reinterpret_cast<char *>(&header), sizeof(header));

// validate the header, get the size in bytes of the bitmap data
size_t bitmapSizeBytes = width * height * channels; // or something like that...

// Now read the bitmap. Use a vector to simplify memory management:
std::vector<unsigned char> bitmap;
bitmap.resize(bitmapSizeBytes);

file.read(reinterpret_cast<char *>(&bitmap[0]), bitmapSizeBytes);


来源:https://stackoverflow.com/questions/23644633/cannot-read-bitmapfileheader-of-a-bitmap-file-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!