我的代码在尝试创建BMP文件时失败

My code fails while attempting to create a BMP file

本文关键字:BMP 文件 失败 创建 代码 我的      更新时间:2023-10-16

我正在尝试创建一个.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);
}

一个典型的错误:返回一个指向局部变量的指针,该指针在离开函数后立即被销毁。指针最终指向胡言乱语或更糟的地方。

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

这对我来说不太合适:

New.Signature='BM';

你当然想要:

New.Signature = *(short*)"BM";