Search code examples
c++arraysbmp

Reading .bmp(24 bit) into a 2D array


I'm a complete beginner to this.I'll try to explain myself as much as i can.

int i, j;
string filename;
cout << "Please enter the file name: " << endl; 
cin >> filename; 
fstream stream;

stream.open(filename.c_str(), 
    ios::in|ios::out|ios::binary);

int file_size = get_int(stream, 2); 
int start = get_int(stream, 10); 
int width = get_int(stream, 18); 
int height = get_int(stream, 22);

This part should get the file and it's values.

for ( i = 0; i < height; i++ )
    {
        for ( j = 0; j < width; j++)
        {
            for (int k = 0; k < split*split; k++){

                int pos = stream.tellg();
                int blue = stream.get(); 
                int green = stream.get(); 
                int red = stream.get();

And this reaches inside each pixel and gets RBG values.

What i want is to first store RBG values into a 2D array and then do some manipulations on that array.Then i'd like to create a new file with manipulated image.

I've no clue so some instructions along with some code would be really helpfull.


Solution

  • Bmp file format is documented in many places. For example, on wikipedia.

    The easiest way would be to implement structure that describes bmp header, and read entire structure in one go, then read individual pixels.

    Your reading function is broken and doesn't function because you did not read file signature - "BM" field of the header.

    On some operating system all there are already strcutures and functions for reading BMPs. On windows, there's BITMAPFILEHEADER. Using those structures means you aren't using "pure C++".

    If you still want to read BMP yourself, read msdn articles aboud bmp or google for "read bmp file" tutorials.