c++ - 尝试创建 BMP 文件时我的代码失败

标签 c++

我正在尝试创建一个 .bmp 文件,但无法识别该文件。我做错了什么?

#define ImageWidgh  1920
#define ImageHeight 1080
#define fileSize ImageWidgh*ImageHeight*3+54

struct BMPH
{
    short Signature;
    long int FileSize,reserved,DataOffest;
}BMPH;
struct BMPIH
{
    long int Size,Width,Height;
    short Planes,BitCount;
    long int Compression,ImageSize,XpixelsPerM,YpixelsPerM,ColorsUsed,ColorImportant;
}BMPIH;
struct BMPCT
{
    unsigned char Red,Green,Blue;
}BMPCT;
BMPH  *getBMPH()
{
    BMPH New;
    New.Signature='BM';
    New.FileSize=fileSize;
    New.reserved=0;
    New.DataOffest=54;
    return &New;
}
BMPIH *getBMPIH()
{
    BMPIH New;
    New.Size=40;
    New.Width=ImageWidgh;
    New.Height=ImageHeight;
    New.Planes=1;
    New.BitCount=24;
    New.Compression=0;
    New.ImageSize=0;
    New.XpixelsPerM=0;
    New.YpixelsPerM=0;
    New.ColorsUsed=0;
    New.ColorImportant=0;
    return &New;
}
BMPCT Pixels [ImageWidgh][ImageHeight];
void writeFile()
{
    FILE *file;
    file=fopen("D://test.bmp","wb");
    fwrite(getBMPH() ,sizeof(BMPH) ,1,file);
    fwrite(getBMPIH(),sizeof(BMPIH),1,file);
    fwrite(&Pixels   ,ImageWidgh*ImageHeight*3,1,file);
    fclose(file);
}

最佳答案

一个典型的错误:你返回的是一个指向局部变量的指针,一旦你离开函数,它就会被销毁。指针最终指向乱码或更糟。

让函数返回完整结构而不是指针,或者将指针传递给函数而不是在函数中创建变量。

关于c++ - 尝试创建 BMP 文件时我的代码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11768652/

相关文章:

c++ - 如何配置 Qt 以使用 SQLite?

c++ - 模板化赋值运算符和自检

c++ - 尝试重载 "+"运算符时收到错误消息说我的类没有命名类型

c++ - matrix = *((fxMatrix*)&d3dMatrix);//邪恶?

c++ - setlocale 是线程安全函数吗?

c++是否对置换算法使用类

c++ - 生成正确的音调频率值

C++ 成功 `try` 分支

c++ - 缩放 QGraphicsItem 以适应 QGraphicsView

c++ - 错误 : no matching function for call to