【发布时间】:2018-04-13 02:33:29
【问题描述】:
我开始关注 Casey Muratori 的优秀手工英雄Stream,最近受到启发,从头开始编写 BMP 图像加载器。
我创建了一个结构来填充位图标题的值
#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)
然后我在入口点填写了值
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;
我创建了一个 32 位无符号整数指针来存储像素数据,然后用颜色写入像素数据。
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;
}
}
最后,我使用标准的 fwrite() 函数将数据写入 bmp 文件
FILE* OutFile = fopen("test.bmp", "wb");
if (OutFile) {
fwrite(&Header, sizeof(Header), 1, OutFile);
fwrite(&OutputPixels, sizeof(OutputPixelSize), 1, OutFile);
fclose(OutFile);
}
程序运行,并创建一个文件;但是任何程序都无法识别上述文件。我将它的标头与有效的 bmp 文件进行了比较,除了文件大小外,它们是相似的。我不知道我是否将数据正确写入文件?
【问题讨论】: