【问题标题】:Difficulty Writing to a Bitmap File难以写入位图文件
【发布时间】: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 文件进行了比较,除了文件大小外,它们是相似的。我不知道我是否将数据正确写入文件?

【问题讨论】:

    标签: c file bitmap bmp


    【解决方案1】:

    OutputPixelSize 是一个uint32_t。因此,sizeof(OutputPixelSize) 将是 4。所以

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

    只向文件写入 4 个字节。

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

    fwrite(OutputPixels, 1, OutputPixelSize, OutFile);
    

    【讨论】:

    • 哦,非常感谢,我每次阅读我的代码时都不知何故错过了 :)
    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2010-12-23
    • 2012-08-26
    • 2012-01-25
    相关资源
    最近更新 更多