0

I am trying to create a .bmp file and file is not recognized. What am I doing wrong?

#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);
}
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
  • 1
    possible padding problems? isn't compiler optimizing by padding your datastructures? did u checked the file in hex editor, whether the fields are of correct size? – Miro Hudak Aug 01 '12 at 22:47

2 Answers2

5

A classic mistake: you're returning a pointer to a local variable, which is destroyed as soon as you leave the function. The pointer ends up pointing to gibberish or worse.

Have the functions return the full structure rather than a pointer, or pass the pointer into the function rather than creating a variable within.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

This doesn't look right to me:

New.Signature='BM';

Surely you want:

New.Signature = *(short*)"BM";
paddy
  • 60,864
  • 6
  • 61
  • 103
  • i changed it to New.Signature = *(short*)"BM"; and its read the file .Thank you all for your help! – user1569875 Aug 01 '12 at 23:13
  • You've never heard of multi-character literals? http://stackoverflow.com/questions/3960954/c-multicharacter-literal. Although you might need to use `'MB'` to account for byte order issues. – Mark Ransom Aug 01 '12 at 23:18
  • @MarkRansom No, actually. I seem to have gotten through 20 years of programming without requiring them! Learn something new every day... Still, that link seems to say the handling of them is implementation-specific, so I'd prefer not to treat it as a "new toy" and go off sprinkling multi-character literals through all my code. – paddy Aug 01 '12 at 23:34