Directly Accessing Pixels in a 24-bit Bitmap
This article was contributed by Zvika Ben-Haim.
Environment: VC5/6, Win95+
This article describes how to display 24-bit (TrueColor) bitmaps which are created during run-time by directly accessing the bitmap's bit image.
The code in this article uses the CDib class, developed by David J. Kruglinski in his book Inside Visual C++, 4th edition. The CDib class is copyrighted by Microsoft, and can be used in your programs as long as you mention their name. The CDib class is included at the end of this document.
1. Create a CDib object, and allocate memory.
This will typically be done in CView::OnInitialUpdate, or some such. It's done in the following way:
2. Fill the bitmap data.
You now have a memory region, allocated by Windows, in which you can write the output information. This memory region is accessed from m_pDib->m_lpImage, and contains a series of three-byte (R,G,B) pixels. As an example, you can get a nice rainbow-color image using the following code:
Where we used the function doc, defined as follows (intended for bitmaps of size 512x512 pixels, more or less):
3. Display the bitmap.
From within CView::OnDraw, use the following to display the bitmap:
where m_rectDraw is a logical-coordinate rectangle defining the position in which we want to place the bitmap. The bitmap is shrunk or expanded using the StretchDIBits function so that it will fit into this rectangle.
4. Delete the DIB.
Don't forget to deallocate the CDib object when you're done. The constructor deallocates all memory associate with the DIB, including the memory of the actual image.
File: CDib.h -- CDib class header file
File: CDib.cpp -- CDib class definitions