【问题标题】:Reading from BMP file into BMP header structures in C从 BMP 文件读入 C 中的 BMP 头结构
【发布时间】:2014-05-22 22:56:17
【问题描述】:

我正在尝试获取一个 BMP 文件并将其读入,然后对其中的像素执行操作以更改其颜色。我的问题是我无法将文件中的数据读入两个 BMP 标头结构。我能够很好地将所有数据读入第一个结构,但是在读入第二个结构时出现段错误。从代码中可以看出,第一个结构 FILEHEADER 被读取并包含它应该包含的所有正确数据,但第二个结构 BMPInfoHeader 没有被正确读取。为什么会出现这个段错误?

#include <stdio.h>
#include <stdlib.h>

typedef struct
{   unsigned short int Type; /* Magic identifier */ 
    unsigned int Size; /* File size in bytes */ 
    unsigned short int Reserved1, Reserved2; 
    unsigned int Offset; /* Offset to data (in B) */
}   FILEHEADER; /* 14 Bytes */

typedef struct
{   unsigned int Size; /* Header size in bytes */ 
    int Width, Height; /* Width / Height of image */ 
    unsigned short int Planes; /* Number of colour planes */ 
    unsigned short int Bits; /* Bits per pixel */ 
    unsigned int Compression; /* Compression type */ 
    unsigned int ImageSize; /* Image size in bytes */ 
    int xResolution, yResolution;/* Pixels per meter */ 
    unsigned int Colors; /* Number of colors */ 
    unsigned int ImportantColors;/* Important colors */ 
} BMPInfoHeader;  /* 40 Bytes */

typedef struct 
{   unsigned char r; /* Red */
    unsigned char b; /* Blue */
    unsigned char g; /* Green */
} IMAGE;

int main(int argc, char *argv[]) {

    FILE *BMPFile;
    FILEHEADER BMPFileHeader;
    BMPInfoHeader *InfoHeader;
    BMPFile=fopen(argv[1],"rb");
    unsigned char *BMPimage;

    if (BMPFile==NULL) {
        printf("\n\nERROR: File not opened properly\n\n");
        return -1;
    }

    fread(&BMPFileHeader,sizeof(unsigned char),14,BMPFile);
    fseek(BMPFile,BMPFileHeader.Offset,SEEK_SET);
    fread(InfoHeader,sizeof(unsigned char),40,BMPFile);

    if (BMPFileHeader.Type != 0x4D42) {
        printf("\n\nERROR with fread\n\n");
        return -1;
    }

        return 0;
 }

【问题讨论】:

标签: c segmentation-fault fread bmp


【解决方案1】:

问题是您定义的FILEHEADER 未对齐,因此编译器将在字段之间插入填充。读取bmp header的正常方式是将2字节的magic number拆分出来单独读取:

typedef struct
{
    unsigned int Size; /* File size in bytes */ 
    unsigned short int Reserved1, Reserved2; 
    unsigned int Offset; /* Offset to data (in B) */
}   FILEHEADER; /* 12 Bytes */

   :

char Magic[2];
FILEHEADER BMPFileHeader;
fread(Magic, 1, 2, BMPFile);
fread(&BMPFileHeader, 1, 12, BMPFile);

如果您在大端机器上运行它,由于字节顺序,这仍然会出现问题。为全面起见,您需要将文件内容读取为字节并手动构造多字节值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2015-05-15
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多