Take for example the classic 24-bit BMP. It is required to paint on it, say, in black a point with the coordinate (x,y) . Pixel data is presented in a one-dimensional array.

Since the BMP file is read from the end, it is logical to present the sought coordinate as m_pBits[((m_nHeight-y-1)*m_nWidth+m_nWidth-x-1)*3] (+1 and +2 for the green and red components) .

But as a result of the program, all points are located with an offset! That is, if a point has a coordinate (0,0) , then it is displayed as (смещение, 0) .

How to correctly represent a point with given coordinates in a one-dimensional array?

    2 answers 2

    Despite its apparent simplicity, the BMP format is a scary dark forest with a bunch of options for internal presentation (estimate the length of the article in Wikipedia)

    So you should use any library, or even the standard WINDOWS functions , to draw in BMP.

    It is easy to fight alignment: write / read at once with structures of the form:

     typedef unsigned char uchar; struct PixelData { uchar B; uchar G; uchar R; uchar alignment; }; PixelData pixel; std::ifstream inf("test.bmp", std::ifstream::binary); inf.read(&pixel, sizeof(PixelData)); 

    When processing, just ignore the alignment bit.

    Well, navigate inside the file:

     // Игнорируем заголовки файла и самого Bitmap const size_t header = sizeof(BITMAPINFO) + sizeof(BITMAPFILEHEADER); size_t pixel_index = 3; inf.seekg( header + sizeof(PixelData) * pixel_index ); 

    PS BMP can store pixels, rows of pixels in different ways, so you should really look at the finished code. But if we are dealing with a certain kind of view, then such a simple “bicycle” will come out easier.

    • It is better to load the header and take the offset from it. And the embarrassment can come out. - gbg
    • @gbg Maybe. But it should not) - free_ze