2017-10-31 6 views
1

私はCasey Muratoriの優れた手作りヒーローStreamに従い始めました。最近、BMPイメージローダーの書き方が最初から書かれています。ビットマップファイルに書き込むのが難しい

Iはビットマップヘッダ

#pragma pack(push, 1) 
struct bitmap_header { 
    uint16_t FType; 
    uint32_t FSize; 
    uint16_t Reserved_1; 
    uint16_t Reserved_2; 
    uint32_t BitmapOffset; 
    uint32_t Size; 
    int32_t Width; 
    int32_t Height; 
    uint16_t Planes; 
    uint16_t BitsPerPixel; 
    uint32_t Compression; 
    uint32_t SizeOfBMP; 
    int32_t HorzResolution; 
    int32_t VertResolution; 
    uint32_t ColorsUsed; 
    uint32_t ColorsImportant; 
}; 
#pragma pack(pop) 

の値を記入するために単一の構造を作成し、私は32ビットの符号なし整数のポインタを作成したエントリポイントで

bitmap_header Header = {}; 
Header.FType = 0x4D42; // Magic Value Here 
Header.FSize = sizeof(Header) + OutputPixelSize; // entire file size 
Header.BitmapOffset = sizeof(Header); 
Header.Size = sizeof(Header) - 14; // Size of the Header exluding the above 
Header.Width = OutputWidth; 
Header.Height = -(int32_t)OutputHeight; 
Header.Planes = 1; 
Header.BitsPerPixel = 24; 
Header.Compression= 0; 
Header.SizeOfBMP = OutputPixelSize; 
Header.HorzResolution = 0; 
Header.VertResolution = 0; 
Header.ColorsUsed = 0; 
Header.ColorsImportant = 0; 

の値を記入画素データを記憶しておき、色付きの画素データを書き込む。

uint32_t OutputPixelSize = sizeof(uint32_t) * OutputWidth * OutputHeight; 
uint32_t *OutputPixels = (uint32_t *)malloc(OutputPixelSize); 

uint32_t *Out = OutputPixels; 
for (uint32_t Y = 0; Y < OutputHeight; ++Y) { 
    for (uint32_t X = 0; X < OutputWidth; ++X) { 
     *Out++ = 0xFF0000FF; 
    } 
} 

は最後に、私は、プログラムが実行され、ファイルが作成され

FILE* OutFile = fopen("test.bmp", "wb"); 
if (OutFile) { 
    fwrite(&Header, sizeof(Header), 1, OutFile); 
    fwrite(&OutputPixels, sizeof(OutputPixelSize), 1, OutFile); 
    fclose(OutFile); 
} 

標準fwriteの()関数を使用して、BMPファイルにデータを書きました。しかし、上記のファイルはどのプログラムでも認識されません。私はそれが有効なbmpファイルとヘッダーを比較し、ファイルサイズ以外は似ています。私はファイルに正しくデータを書いているかどうか分かりません。

答えて

0

OutputPixelSizeは、uint32_tです。そしてsizeof(OutputPixelSize)そのためだけのファイルに4つのバイトを書き込みますので

fwrite(&OutputPixels, sizeof(OutputPixelSize), 1, OutFile); 

4になります。

さらに&OutputPixelsは、データへのポインタではなく、データへのポインタのアドレスあります。代わりにOutputPixelsfwriteに渡す必要があります。試してみてください:

fwrite(OutputPixels, 1, OutputPixelSize, OutFile); 
+0

大変ありがとうございます、私は何とか私のコードを読むたびに逃しました:) – xsnk

関連する問題