Gábor Buella
Gábor Buella

Reputation: 1920

Can the width field in a BMP with BITMAPINFOHEADER be negative?

I recently found out BMP images can have negative height, meaning the pixels are stored top-to-bottom in the file. Our production code rejected a file from a user, as it interpreted the height as 4294966272 ( unsigned 32 bit value ) , while the it really was -1024 ( signed 32 bit value ) , actually meaning a height of 1024 pixels. The most "official" documentation of BITMAPINFOHEADER format I managed to find is on Wikipedia, which says the width is also a signed integer. How would one correctly validate a BMP input?

Upvotes: 2

Views: 1532

Answers (2)

Limitless1
Limitless1

Reputation: 1

Change from unsigned 32bit to signed 32bit That should fix it

Upvotes: 0

yms
yms

Reputation: 10418

Since the BMP format has been used in Windows since version 2.0 I would use MSDN as the most "official" documentation. In MSDN we find the following definition of BITMAPINFOHEADER:

typedef struct tagBITMAPINFOHEADER {
  DWORD biSize;
  LONG  biWidth;
  LONG  biHeight;
  WORD  biPlanes;
  WORD  biBitCount;
  DWORD biCompression;
  DWORD biSizeImage;
  LONG  biXPelsPerMeter;
  LONG  biYPelsPerMeter;
  DWORD biClrUsed;
  DWORD biClrImportant;
} BITMAPINFOHEADER, *PBITMAPINFOHEADER;

As you can see, biHeight is defined as long, which is usually the same as signed int. If your code is not reading this value properly, I would say that there is a bug there somewhere.

Upvotes: 0

Related Questions