c - 在c中读/写bmp文件

标签 c bitmap

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

它们大小相同,标题似乎也相同。 有什么问题? 谢谢。

最佳答案

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

关于c - 在c中读/写bmp文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11129138/

相关文章:

c - 加密字符串与测试 vector 不同

c - 链表指针问题

c - 在gdb中调试时如何检查哪个文件声明了变量?

java - Bitmap.compress - 不工作

android - 如何避免位图图像的空值

c++ - 计算单色 BMP 的 BITMAPINFOHEADER biCompression 值

android - 在不创建位图的情况下获取 Drawable 的 byte[]

c - 如何阻止命令提示符出现在 Win32 C 应用程序中?

c - 我如何使用 C 语言中的 stdarg 编写该代码

android - Android 中的缓冲图像