2012-06-20 203 views
8

我正在尝试使用bmp文件。 用于起动I试图从bmp文件读取的报头和数据,并且将其写入到一个新的文件:在c中读取/写入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

+0

@TheZ:图像数据由b,g,r阶的每像素三个字节组成。数据按行先存储,按行逐行存储,每行按零填充长度为4个字节的倍数。我只是写回我读过的东西。这是个问题吗? – Sanich

+1

那么,弹出在十六进制编辑器中打开这两个文件并进行比较。快速查看显示它们在标题之后的长度和数据是不同的。 – TheZ

回答

7

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

+0

工程!谢谢。 – Sanich