难以写入位图文件

时间:2017-10-31 19:58:04

标签: c file bitmap bmp

我开始关注Casey Muratori的优秀手工英雄Stream,并且最近受到启发,从头开始编写BMP图像加载器。

我创建了一个单独的结构来填充位图标题的值

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;
    }
}

我创建了一个32位无符号整数指针来存储像素数据,然后用颜色写入像素数据。

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

最后,我使用标准的fwrite()函数将数据写入bmp文件

{{1}}

程序运行,并创建一个文件;但是上述文件不被任何程序识别。我将它的头部与有效的bmp文件进行了比较,除文件大小外,它们是相似的。我不知道我是否正确地将数据写入文件?

1 个答案:

答案 0 :(得分:0)

OutputPixelSizeuint32_t。因此sizeof(OutputPixelSize)将是4.所以

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

仅向文件写入4个字节。

此外&OutputPixels是指向数据的指针的地址,而不是指向数据的指针。您应该将OutputPixels传递给fwrite。尝试:

fwrite(OutputPixels, 1, OutputPixelSize, OutFile);