After writing BMP file, image is flipped upside down
Asked Answered
A

2

6

I am using the following code:

f = fopen( _stringhelper.STR("%s.bmp", filename), "wb" );
if( !f ) {
    _core.Error( ERC_ASSET, "ncImageLoader::CreateImage - Couldn't create %s image.\n", filename );
    return false;
}

int w = width;
int h = height;
int i;

int filesize = 54 + 3 * w * h;

byte bmpfileheader[14] = {
    'B', 'M',
    0, 0, 0, 0,
    0, 0,
    0, 0,
    54, 0, 0, 0 };

byte bmpinfoheader[40] = { 40, 0, 0, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    1, 0,
    24, 0};

byte bmppad[3] = { 0, 0, 0 };

bmpfileheader[2] = (byte)( filesize );
bmpfileheader[3] = (byte)( filesize >> 8 );
bmpfileheader[4] = (byte)( filesize >> 16 );
bmpfileheader[5] = (byte)( filesize >> 24 );

bmpinfoheader[4] = (byte)( w );
bmpinfoheader[5] = (byte)( w >> 8);
bmpinfoheader[6] = (byte)( w >> 16  );
bmpinfoheader[7] = (byte)( w >> 24);
bmpinfoheader[8] = (byte)( h );
bmpinfoheader[9] = (byte)( h >> 8 );
bmpinfoheader[10] = (byte)( h >> 16 );
bmpinfoheader[11] = (byte)( h >> 24 );

fwrite( bmpfileheader, 1, 14, f );
fwrite( bmpinfoheader, 1, 40, f );

for( i = 0; i < h; i++ ) {
    fwrite( data + ( w * (h - i - 1) * 3 ), 3, w, f );
    fwrite( bmppad, 1, ( 4 - ( w * 3 ) % 4 ) % 4, f );
}

fclose(f);

I am using glReadPixels() to capture the display data. If I go to the folder where I saved this file and open it - it's fine, color palette is good, but it is flipped upside down. I've tried to write the for loop "backwards" but still nothing.. I don't get it.

What may be the problem?

Amphigory answered 1/10, 2014 at 15:30 Comment(1)
Can you show your backwards for loop? (The current one is actually "backwards" but that's because BMP expects it.)Specs
P
11

Bitmaps are stored "upside-down", see more about that here:

Why are bmps stored upside down?

You could set the height as a negative value to have it displayed correctly. (-height)

From MSDN site, BITMAPINFOHEADER:

If biHeight is negative, the bitmap is a top-down DIB with the origin at the upper left corner.

Prolonge answered 22/10, 2014 at 18:20 Comment(0)
A
3

BMP File Format Structure

BMP File Format

  • For uncompressed RGB bitmaps, if Height is positive, the bitmap is a bottom-up DIB(device-independent bitmap) with the origin at the lower left corner. BottomUP

  • If Height is negative, the bitmap is a top-down DIB with the origin at the upper left corner. TopDown

  • For YUV bitmaps, the bitmap is always top-down, regardless of the sign of Height. Decoders should offer YUV formats with positive Height, but for backward compatibility they should accept YUV formats with either positive or negative Height.

  • For compressed formats, Height must be positive, regardless of image orientation.

Source: https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader?redirectedfrom=MSDN

Aunt answered 18/2, 2022 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.