在C语言中读写BMP文件

8

我正在尝试处理一个bmp文件。 首先,我尝试从bmp文件中读取头部和数据,并将其写入新文件:

#pragma pack(push,1)
/* Windows 3.x bitmap file header */
typedef struct {
    char         filetype[2];   /* magic - always 'B' 'M' */
    unsigned int filesize;
    short        reserved1;
    short        reserved2;
    unsigned int dataoffset;    /* offset in bytes to actual bitmap data */
} file_header;

/* Windows 3.x bitmap full header, including file header */
typedef struct {
    file_header  fileheader;
    unsigned int headersize;
    int          width;
    int          height;
    short        planes;
    short        bitsperpixel;  /* we only support the value 24 here */
    unsigned int compression;   /* we do not support compression */
    unsigned int bitmapsize;
    int          horizontalres;
    int          verticalres;
    unsigned int numcolors;
    unsigned int importantcolors;
} bitmap_header;
#pragma pack(pop)

int foo(char* input, char *output) {

    //variable dec:
    FILE *fp,*out;
    bitmap_header* hp;
    int n;
    char *data;

    //Open input file:
    fp = fopen(input, "r");
    if(fp==NULL){
        //cleanup
    }


    //Read the input file headers:
    hp=(bitmap_header*)malloc(sizeof(bitmap_header));
    if(hp==NULL)
        return 3;

    n=fread(hp, sizeof(bitmap_header), 1, fp);
    if(n<1){
        //cleanup
    }

    //Read the data of the image:
    data = (char*)malloc(sizeof(char)*hp->bitmapsize);
    if(data==NULL){
        //cleanup
    }

    fseek(fp,sizeof(char)*hp->fileheader.dataoffset,SEEK_SET);
    n=fread(data,sizeof(char),hp->bitmapsize, fp);
    if(n<1){
        //cleanup
    }

        //Open output file:
    out = fopen(output, "w");
    if(out==NULL){
        //cleanup
    }

    n=fwrite(hp,sizeof(char),sizeof(bitmap_header),out);
    if(n<1){
        //cleanup
    }
    fseek(out,sizeof(char)*hp->fileheader.dataoffset,SEEK_SET);
    n=fwrite(data,sizeof(char),hp->bitmapsize,out);
    if(n<1){
        //cleanup
    }

    fclose(fp);
    fclose(out);
    free(hp);
    free(data);
    return 0;
}

这是输入文件: enter image description here 这是输出结果: enter image description here 它们的大小相同,似乎也具有相同的标题。 可能出了什么问题? 谢谢。

1
位图像素数据在行中必须是32位对齐的。您确定这不是问题吗? - TheZ
@TheZ:图像数据每个像素由三个字节组成,顺序为b,g,r。数据按行优先顺序存储,逐行排列,每行末尾用零填充至长度为4字节的倍数。我只是在回复你我所读到的内容。这是有问题吗? - Sanich
1
那么,打开十六进制编辑器并比较这两个文件。快速查看后发现它们在头部之后的长度和数据不同。 - TheZ
4
这是什么?这是一个C++程序的主函数,其输入和输出参数分别为指向字符数组的指针。 - AusCBloke
1
@ AusCBloke:只是一个函数的名称。 - Sanich
1个回答

7
我猜您应该以二进制模式打开文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接