【问题标题】:reading/writing bmp files in c在c中读/写bmp文件
【发布时间】:2012-06-23 03:43:32
【问题描述】:

我正在尝试处理 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;
}

这是输入文件:

这是输出:

它们的大小相同,并且似乎具有相同的标题。 有什么问题? 谢谢。

【问题讨论】:

  • 位图像素数据必须在行中以 32 位对齐。你确定这不是问题吗?
  • @TheZ:图像数据按 b、g、r 顺序由每个像素三个字节组成。数据按行优先顺序、一行接一行地存储,每一行都用零填充,长度为 4 字节的倍数。我只是把我读过的东西写回来。有问题吗?
  • 好吧,然后在十六进制编辑器中弹出打开这两个文件并进行比较。快速浏览会发现它们在标题后的长度和数据不同。
  • int main(char* input, char *output) - 这是什么?
  • @AusCBloke:只是函数的名称。

标签: c bitmap


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2014-05-22
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多