2012-06-20 2 views
8

私は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

、これは出力されるiはBMPファイルからヘッダとデータを読み取るために、新しいファイルに書き込みしようとした開始の : enter image description here

これらは同じサイズで、同じヘッダーを持つようです。 何が間違っていますか?おかげさまで

+1

ビットマップピクセルデータは、32ビットの行で整列する必要があります。これは問題ではないと確信していますか? – TheZ

+0

@ TheZ:画像データは、ピクセルごとにb、g、rの3バイトで構成されます。データは行優先順、行後行に格納され、すべての行は4バイトの倍数である0にパディングされます。私は読んだことだけを書き返しています。それって問題ですか? – Sanich

+1

次に、両方のファイルを16進エディタでポップアップして比較します。クイックルックでは、ヘッダーの後ろに長さとデータが異なることがわかります。 – TheZ

答えて

7

バイナリモードでファイルを開く必要があると推測します。

+0

作品!!!ありがとう。 – Sanich

関連する問題