David Spears
David Spears

Reputation: 39

Height and Width of Image using C++

Is there a way of finding the height and width from the *.bmp file either through its header file or another way? I'm currently using Visual Studio 2010. I recognise that the header file is 54 bytes.

I currently have this:

ifstream image;
image.open("image.bmp",std::ios_base::binary);

if (image.is_open()) 
{
cout<< "function success\n";
} 
else 
{
cout<< "unable to open file";
}
//get length of file:
image.seekg(0, image.end);
int n = image.tellg();
image.seekg (0, image.beg);

//allocate memory:
char* res = new char[n];

//read data as a block:
image.read(res, n);

Is there a way I can loop through to extract the relevant information? I would appreciate an example if possible.

Thanks in advance.

Upvotes: 3

Views: 1713

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490108

A BMP file has a BITMAPFILEHEADER followed immediately by a BITMAPINFOHEADER or BITMAPCOREINFO.

The latter two contain the height/width of the bitmap.

If you want to do this in Windows, I'd use the definitions of those structures from windows.h. If you're doing it on Linux or elsewhere, you can use the definitions from MSDN (and be sure to set the compiler to ensure there's no packing between fields of the structures).

With that, you can read in the structures, and read out the pieces you care about. I suppose you could seek to the correct offsets and then read the correct number of bytes from there, but I'd read the entire structs instead. It's simple and either way you're going to read one disk sector, so you're unlikely to gain speed or anything like that.

Upvotes: 4

Related Questions