简体   繁体   English

读取位图图像时获取错误数据

[英]Getting wrong data while reading Bitmap image

I'm following this tutorial http://www.gamedev.net/page/resources/_/technical/game-programming/how-to-load-a-bitmap-r1966 and I got the problem of wrong value for all the bitmap header/info that I load. 我正在按照本教程http://www.gamedev.net/page/resources/_/technical/game-programming/how-to-load-a-bitmap-r1966进行操作 ,但我发现所有我加载的位图标题/信息。

I've declared the structure to store the bitmap header, info 我已经声明了存储位图标题信息的结构

typedef struct BITMAPFILE_HEADER {
  WORD  bfType;
  DWORD   bfSize;
  WORD  bfReserved1;
  WORD  bfReserved2;
  DWORD   bfOffBits;
} BITMAPFILE_HEADER;

//Bitmap information header
//provides information specific to the image data
typedef struct BITMAPINFO_HEADER{
  DWORD  biSize;
  LONG   biWidth;
  LONG   biHeight;
  WORD   biPlanes;
  WORD   biBitCount;
  DWORD  biCompression;
  DWORD  biSizeImage;
  LONG   biXPelsPerMeter;
  LONG   biYPelsPerMeter;
  DWORD  biClrUsed;
  DWORD  biClrImportant;
} BITMAPINFO_HEADER;

//Colour palette
typedef struct RGB_QUAD {
  BYTE  rgbBlue;
  BYTE  rgbGreen;
  BYTE  rgbRed;
  BYTE  rgbReserved;
} RGB_QUAD;

After that I read the bitmap by using following codes: 之后,我通过使用以下代码读取位图:

    FILE *in;
    in = fopen("picture.bmp", "rb");

    if (in == NULL)
    {
        printf("Error opening file\n");
    }
    else
    {
        BITMAPFILE_HEADER bmfh;
        BITMAPINFO_HEADER bmih;

        fread(&bmfh, sizeof(BITMAPFILE_HEADER), 1, in);
        fread(&bmih, sizeof(BITMAPINFO_HEADER), 1, in);

        if (bmih.biBitCount != 24)
            printf("not 24");
    }

My picture is 24-bit but when I run this program, it shows "not 24". 我的图片是24位的,但是当我运行该程序时,它显示为“ not 24”。 I try to debug it in Visual Studio then I saw the bmih.biBitCount is 0 . 我尝试在Visual Studio中调试它,然后看到bmih.biBitCount0 In addition, the image width and height is wrong as well, the only correct data that I found in the header is the bmfh.bfType which is 19778 . 另外,图像的宽度和高度也是错误的,我在标头中找到的唯一正确数据是bmfh.bfType ,它是19778

Anyone know what's wrong with my codes? 有人知道我的代码有什么问题吗? Again, I just want to read the bmp but not displaying it. 同样,我只想读取bmp而不显示它。

PS: Originally the picture is in JPEG format. PS:最初图片为JPEG格式。 I converted it to BMP format by using MS PAINT and re-save it in BMP format. 我使用MS PAINT将其转换为BMP格式,然后将其重新保存为BMP格式。 I wonder does it affect the values? 我想知道这会影响价值吗?

I would imagine that you ran into an alignment issue , because the compiler can choose to align data in a structure as he sees fit. 我想您会遇到对齐问题 ,因为编译器可以选择按他认为合适的方式对齐结构中的数据。 You can try to pack your struct, but I would suggest to read out every field and fill it in separately, it is more work, but it is clearer and avoids alignment issues. 您可以尝试打包您的结构,但是我建议您读出每个字段并将其分别填写,这是更多的工作,但是它更清晰并且避免了对齐问题。

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

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