Bitmaps
The bitmapped image, or simply bitmap, is a staple of modern computer graphics because it allows computers to store complex images in the form of 1s and 0s. In Windows, bitmaps are GDI objects that are handled at a fairly high level just like fonts, . brushes, pens, and other GDI objects you can create bitmaps with a paint program, embed them as resources in an application's EXE file, and load them with a simple function call; or you can create bitmaps on the fly by using GDI functions to Draw to Virtual Display Surfaces in Memory. Once Created, A Bitmap Can Be Displayed On The Screen Or Reproduces ON The Printer with a Few Simple Function Calls.
Two types of bitmaps are supported in 32-bit Windows:. Device-dependent bitmaps (DDBs) and device-independent bitmaps (DIBs) Also supported in 32-bit Windows is a variation on the device-independent bitmap that was first introduced in Windows NT-something programmers refer to as a DIB section. DDBs are the simplest of the lot as well as the most limiting. They also happen to be the only type of bitmap that MFC thoroughly encapsulates. We'll get the fundamentals out of the way first by covering CBitmaps and DDBs, and later we'll move on to the more powerful DIBs and DIB sections. As you read, be aware that I'll often use the term bitmap interchangeably with the more specific terms DDB, DIB, and DIB SECTION. Which Type of Bitmap I'm Referring to (or WHETHER I'M Using The Term generical) SHOULD BE CLEAR from the Context of the discussion.
DDBS and the cbitmap class
It goes without saying that before you can do anything with a bitmap, you must first create it One way to create a bitmap is to construct a CBitmap object and call CBitmap :: CreateCompatibleBitmap:. CBitmap bitmap;
Bitmap.createCompAtibleBitmap (& DC, NWIDTH, NHEIGHT);
In this example, dc represents a screen device context and nWidth and nHeight are the bitmap's dimensions in pixels. The reason CreateCompatibleBitmap requires a device context pointer is that the format of the resulting DDB is closely tied to the architecture of the output device. Providing a pointer to a device context enables Windows to structure the DDB so that it's compatible with the device on which you intend to display it. The alternative is to call CBitmap :: CreateBitmap or CBitmap :: CreateBitmapIndirect and specify the number of color planes and number of bits per pixel per color plane, both of which are device-dependent values. These days, about the only practical use for CreateBitmap and CreateBitmapIndirect is for creating monochrome bitmaps. Monochrome bitmaps are sometimes useful even in color environments, as one of this chapter's sample Program Will Demonstrate.
A DDB created with CreateCompatibleBitmap initially contains random data. If you want to do something with the DDB-say, display it in a window-you'll probably want to draw something into the bitmap first. You can use GDI functions to draw into a bitmap by first creating a special type of device context known as a memory device context (DC) and then selecting the bitmap into the memory DC. In essence, a bitmap selected into a memory DC becomes the device context's display surface, just as the display surface that corresponds to a screen DC is the screen itself The following code creates an uninitialized DDB that measures 100 pixels square It then creates a memory DC, selects the bitmap into it, and initializes all the pixels in the bitmap to blue:.. CClientDC DCScreen (this);
CBitmap Bitmap;
Bitmap.createCompatibleBitmap (& DCSCREEN, 100, 100);
CDC DCMEM;
DcMem.createCompatibleDC (& DCScreen);
CBRUSH Brush (RGB (0, 0, 255);
CBITMAP * PoldbitMap = DCMem.selectObject (& Bitmap);
DcMem.FillRect (CRECT (0, 0, 100, 100), & Brush);
DcMem.selectObject (Poldbitmap);
CDC :: CreateCompatibleDC creates a memory DC that's compatible with the specified device context. The device context whose address you pass in is usually a screen DC, but it could just as easily be a printer DC if the image you're preparing is destined for a printer rather than the screen. Once a bitmap is selected into a memory DC, you can draw to the memory DC (and hence into the bitmap) using the same CDC member functions you use to draw to a screen or printer DC.
The big difference between drawing to a memory DC and drawing to a screen DC is that pixels drawn to a memory DC are not displayed. To display them, you have to copy them from the memory DC to a screen DC. Drawing to a memory DC first and then transferring pixels to a screen DC can be useful for replicating the same image on the screen several times. Rather than draw the image anew each time, you can draw it once in a memory DC and then transfer the image to a screen DC as many times as you want. (Be aware, however, that many display adapters will perform better if you copy the image from the memory DC to the screen DC one time and then replicate the image already present in the screen DC as needed. ) Bitmaps play an important role in the process because when a memory DC is first created it contains just one pixel you can draw to, and that pixel is a monochrome pixel. Selecting a bitmap into a memory DC gives you a larger display surface to draw On and Also More Colors to Work with as LO Ng as the bitmap isn't monochrome.blitting Bitmaps to screens and other devices
How do you draw a bitmap on the screen Bitmaps can not be selected into nonmemory DCs;?. If you try, SelectObject will return NULL But you can use CDC :: BitBlt or CDC :: StretchBlt to "blit" pixels from a memory DC to a screen DC BitBlt transfers a block of pixels from one DC to another and preserves the block's dimensions;.. StretchBlt transfers a block of pixels between DCs and scales the block to the dimensions you specify If dcMem is a memory DC that contains a 100-Pixel by 100-Pixel Bitmap Image and DCScreen Is A Screen DC, The Statement
Dcscreen.bitblt (0, 0, 100, 100, & DCMEM, 0, 0, SRCCOPY);
copies the image to the screen DC and consequently displays it on the screen. The first two parameters passed to BitBlt specify the coordinates of the image's upper left corner in the destination (screen) DC, the next two specify the width and height of the block to be transferred, the fifth is a pointer to the source (memory) DC, the sixth and seventh specify the coordinates of the upper left corner of the block of pixels in the source DC, and the eighth and final parameter specifies the type of raster operation to be used in the transfer. SRCCOPY copies the pixels unchanged from the memory DC to the screen DC.You can shrink or expand a bitmap as it's blitted by using StretchBlt instead of BitBlt. StretchBlt's argument list looks a lot like BitBlt's, but it . includes an additional pair of parameters specifying the width and height of the resized image The following statement blits a 100-by-100 image from a memory DC to a screen DC and stretches the image to fit a 50-by-200 rectangle:
Dcscreen.stretchblt (0, 0, 50, 200, & DCMEM, 0, 0, 100, 100, SRCCOPY);
By default, rows and columns of pixels are simply removed from the resultant image when the width or height in the destination DC is less than the width or height in the source DC. You can call CDC :: SetStretchBltMode before calling StretchBlt to specify other stretching modes that use various methods to preserve discarded color information. Refer to the documentation on SetStretchBltMode for further details, but be advised that the most potentially useful alternative stretching mode-HALFTONE, which uses dithering to simulate colors that can not be displayed directly-works In Windows NT and Windows 2000 But Not in Windows 95 and Windows 98.
You Can Get Information About a Bitmap by Passing a PoinTer To A Bitmap Structure To CBitmap :: getBitmap. Bitmap is defined as flollows: typedef struct tagbitmap {
Long BMTYPE;
Long BMWIDTH;
Long bmheight;
Long BMWIDTHBYTES;
Word bmplanes;
Word Bmbitspixel;
LPVOID BMBITS;
} Bitmap;
The bmType field always contains 0. bmWidth and bmHeight specify the bitmap's dimensions in pixels. BmWidthBytes specifies the length (in bytes) of each line in the bitmap and is always a multiple of 2 because rows of bits are padded to 16-bit boundaries. . bmPlanes and bmBitsPixel specify the number of color planes and the number of pixels per bit in each color plane If bm is an initialized BITMAP, you can determine the maximum number of colors the bitmap can contain by using the following statement:
INT ncolors = 1 << (BM.BMPLANES * BM.BMBITSPIXEL);
Finally, BMBITS Contains a Null Pointer Following a call to getBitmap if the bitmap is a ddb. If Bitmap represents a cbitmap object, The Statements
Bitmap BM;
Bitmap.getBitmap (& BM);
INITIALIZE BM WITH INFORMATION About the bitmap.
The bitmap dimensions returned by GetBitmap are expressed in device units (pixels), but both BitBlt and StretchBlt use logical units. If you want to write a generic DrawBitmap function that blits a bitmap to a DC, you must anticipate the possibility that the DC might be set to a mapping mode other than MM_TEXT The following DrawBitmap function, which is designed to be a member function of a class derived from CBitmap, works in all mapping modes pDC points to the device context the bitmap is being blitted to;.. x AND Y Specify The Location of The Image's Upper Left Corner At The Destination:
Void CMYBITMAP :: DRAWBITMAP (CDC * PDC, INT X, INT Y) {
Bitmap BM;
GetBitmap (& BM);
Cpoint size (BM.BMWIDTH, BM.BMHEIGHT);
PDC-> DPTOLP (& size);
CPOINT ORG (0, 0);
PDC-> DPTOLP (& ORG);
CDC DCMEM;
DcMem.createCompatiPLEDC (PDC);
CBITMAP * PoldbitMap = DCMem.selectObject (this);
DcMem.SetmapMode (PDC-> getmapmode ());
PDC-> Bitblt (x, y, size.x, size.y, & dcmem, org.x, org.y, srcopy);
DcMem.selectObject (Poldbitmap);
}
Because of some inadvertent skullduggery that MFC's CDC :: DPtoLP function performs on CSize objects, the size variable that holds the bitmap's dimensions is a CPoint object, not a CSize object. When you pass CDC :: DPtoLP the address of a CPoint object, the call goes straight through to the :: DPtoLP API function and the conversion is performed properly, even if one or more of the coordinates comes back negative. But when you pass CDC :: DPtoLP the address of a CSize object, MFC performs the conversion itself And Converts Any Negatives to Positives. IT Might Make Intuitive Sense That Sizes Shouldn't Be Negative, But That's Exactly What Bitblt Expects in Mapping Modes in Which The Y Axis Points Upward.
Bitmap Resources
If all you want to do is display a predefined bitmap image-one created with the Visual C resource editor or any paint program or image editor that generates BMP files-you can add a bitmap resource to your application's RC file like this:
IDB_MYLOGO BITMAP logo.Bmp
He Can Load it like this:
CBitmap Bitmap;
Bitmap.LoadBitmap (IDB_MYLOGO);
In this example, IDB_MYLOGO is the bitmap's integer resource ID and Logo.bmp is the name of the file that contains the bitmap image You can also assign a bitmap resource a string ID and load it this way:. Bitmap.LoadBitmap (_T ( " MYLOGO "));
LoadBitmap accepts resource IDs of either type. After loading a bitmap resource, you display it the way you display any other bitmap-by selecting it into a memory DC and blitting it to a screen DC. Splash screens like the one you see when Visual C Starts Up Are Typically Stored As Bitmap Resources And Loaded with loadbitmap (or it / ipi equivalent, :: loadbitmap) Just Before They're Displayed.
CBitmap includes a related member function named LoadMappedBitmap that loads a bitmap resource and transforms one or more colors in the bitmap to the colors you specify. LoadMappedBitmap is a wrapper around :: CreateMappedBitmap, which was added to the API so that colors in bitmaps used to Paint Owner-Draw Buttons, Toolbar Buttons, And Other Controls Could Be Transformed Into System Colors Upon Loading. The Statement
Bitmap.LoadMappedBitmap (idb_bitmap);
loads a bitmap resource and automatically transforms black pixels to the system color COLOR_BTNTEXT, dark gray (R = 128, G = 128, B = 128) pixels to COLOR_BTNSHADOW, light gray (R = 192, G = 192, B = 192) pixels To color _btnface, White Pixels to color_btnhighlight, Dark Blue (r = 0, g = 0, b = 128) Pixels to color_highlight, and Magenta (r = 255, g = 0, b = 255) Pixels to color_window. The idea behind mapping magenta to COLOR_WINDOW is that you can add "transparent" pixels to a bitmap by coloring them magenta. If LoadMappedBitmap transforms magenta pixels into COLOR_WINDOW pixels and the bitmap is displayed against a COLOR_WINDOW background, the remapped pixels will be invisible against the window background. you can perform custom color conversions by passing LoadMappedBitmap a pointer to an array of COLORMAP structures specifying the colors you want changed and the colors you want to change them to. One use for custom color mapping is for simulating transparent pixels by transforming an arbitrary background color to the background color of your choice. Later in this chapter, we'll examine a technique for drawing bitmaps with transparent pixels that works with any kind of background (even those that are not solid) and requires no color mapping.
Dibs and Dib Sections
The problem with device-dependent bitmaps is-well, that they're device-dependent. You can manipulate the bits in a DDB directly using CBitmap :: GetBitmapBits and CBitmap :: SetBitmapBits, but because pixel color data is stored in a device- dependent format, it's difficult to know what to do with the data returned by GetBitmapBits (or what to pass to SetBitmapBits) unless the bitmap is monochrome. Worse, the color information encoded in a DDB is meaningful only to the device driver that displays it. If you write a DDB to disk on one PC and read it back on another, there's a very good chance that the colors will not come out the same. DDBs are fine for loading and displaying bitmap resources (although you'll get poor results if a bitmap resource contains more colors than your hardware is capable of displaying) and for drawing images in memory DCs before rendering them on an output device. But their lack of portability makes them unsuitable for just about anything else.
That's why Windows 3.0 introduced the device-independent bitmap, or DIB. The term DIB describes a device-independent format for storing bitmap data, a format that's meaningful outside the context of a display driver and even outside the framework of Windows itself. When you call :: CreateBitmap (the API equivalent of CBitmap :: CreateBitmap) to create a bitmap, you get back an HBITMAP handle. When you call :: CreateDIBitmap to create a bitmap, you also get back an HBITMAP. The difference is what's inside. Pixel data passed to :: CreateBitmap is stored in device driver format, but pixel data passed to :: CreateDIBitmap is stored in DIB format. moreover, the DIB format includes color information that enables different device drivers to interpret colors consistently. The API includes a pair of functions named :: GetDIBits and :: SetDIBits for reading and writing DIB-formatted bits. It also includes functions for rendering raw DIB data stored in a buffer owned by the application to an output devic e. Windows BMP Files Store Bitmaps in Dib Format, So It's Relative To Write a Function That Uses :: CreateDibitmap to Convert The Contents of A Bmp File Into A GDI Bitmap Object.
DIB sections are similar to DIBs and were created to solve a performance problem involving the :: StretchDIBits function in Windows NT. Some graphics programs allocate a buffer to hold DIB bits and then render those bits directly to the screen with :: StretchDIBits. By not passing the bits to :: CreateDIBitmap and creating an HBITMAP, the programs enjoy direct access to the bitmap data but can still display the bitmap on the screen. Unfortunately, the client / server architecture of Windows NT and Windows 2000 dictates that bits blitted from a buffer on the client side be copied to a buffer on the server side before they're transferred to the frame buffer, and the extra overhead causes :: StretchDIBits to perform sluggishly.Rather than compromise the system architecture, the Windows NT team came up with Dib Sections. A DIB Section Is The Windows NT and Windows 2000 Equivalent of Having Your Cake and Eating It: You CAN SELECT A DIB Section Into A DC And Blit It To The Screen (Thus Avoidi ng the undesirable memory-to-memory moves), but you can also access the bitmap bits directly. Speed is not as much of an issue with the :: StretchDIBits function in Windows 95 and Windows 98 because these operating systems are architected differently than Windows NT and Windows 2000, but Windows 95 and Windows 98 support DIB sections just as Windows NT and Windows 2000 do and also offer some handy API functions for dealing with them. Win32 programmers are encouraged to use DIB sections in lieu of ordinary DIBs and DDBs ....................
The bad news about DIBs and DIB sections is that current versions of MFC do not encapsulate them. To use DIBs and DIB sections in your MFC applications, you have to either resort to the API or write your own classes to encapsulate the relevant API functions . Writing a basic CDib class or extending CBitmap to include functions for DIBs and DIB sections is not difficult, but I'm not going to do either here because it's very likely that some future version of MFC will include a comprehensive set of classes representing DIBs and DIB sections. What I'll do instead is show you how to get the most out of MFC's CBitmap class and how to combine CBitmap with API functions to get some very DIB-like behavior out of ordinary CBitmaps.Blits, Raster Operations, And color mapping
The most common use for CDC :: BitBlt is to blit bitmap images to the screen. But BitBlt does more than just transfer raw bits. In reality, it's a complex function that computes the color of each pixel it outputs by using Boolean operations to combine pixels from the source DC, the destination DC, and the brush currently selected in the destination DC The SRCCOPY raster-op code is simple;. it merely copies pixels from the source to the destination Other raster-op codes are not so simple. . MERGEPAINT, for example, inverts the colors of the source pixels with a Boolean NOT operation and ORs the result with the pixel colors at the destination. BitBlt supports 256 raster-op codes in all. The 15 shown in the following table are given names WITH #define statements in wingdi.h.
Bitblt Raster-op Codes
NameBinary EquivalentOperation (s) PerformedSRCCOPY0xCC0020dest = sourceSRCPAINT0xEE0086dest = source OR destSRCAND0x8800C6dest = source AND destSRCINVERT0x660046dest = source XOR destSRCERASE0x440328dest = source AND (NOT dest) NOTSRCCOPY0x330008dest = (NOT source) NOTSRCERASE0x1100A6dest = (NOT src) AND (NOT dest) MERGECOPY0xC000CAdest = (source AND pattern ) MERGEPAINT0xBB0226dest = (NOT source) OR destPATCOPY0xF00021dest = patternPATPAINT0xFB0A09dest = pattern OR (NOT src) OR destPATINVERT0x5A0049dest = pattern XOR destDSTINVERT0x550009dest = (NOT dest) BLACKNESS0x000042dest = BLACKWHITENESS0xFF0062dest = WHITEYou can derive custom raster-op codes by applying the logical operations you want to the .
PAT 1 1 1 1 0 0 0 0
SRC 1 1 0 0 1 1 0 0
DEST 1 0 1 0 1 0 1 0
Pat (for "pattern") represents the color of the brush selected into the destination DC; Src represents the pixel color in the source DC;. And Dest represents the pixel color in the destination DC Let's say you want to find a raster-op code that inverts a source bitmap, ANDs it with the pixels at the destination, and ORs the result with the brush color First apply these same operations to each column of bits in the list The result is shown here..:
PAT 1 1 1 1 0 0 0 0
SRC 1 1 0 0 1 1 0 0
DEST 1 0 1 0 1 0 1 0
-------------------------------------------- 1 1 1 1 1 0 0 1 0 = 0xf2
Look up 0xF2 in the ternary raster operations table, and you'll find that the full raster-op code is 0xF20B05. Consequently, you can pass BitBlt the hex value 0xF20B05 instead of SRCCOPY or some other raster-op code and it will perform the Raster Operation Described Above.
So what can you do with all those raster-op codes? The truth is that in color environments you probably will not use many of them. After SRCCOPY, the next most useful raster operations are SRCAND, SRCINVERT, and SRCPAINT. But as the Sample Program in The next section DemonStrates, Using An Unnamed Raster-Op Code Can Sometimes Reduce The Number of Stes Required To Achieve A Desired Result.
BitBlt is part of a larger family of CDC blitting functions that includes StretchBlt (which we've already discussed), PatBlt, MaskBlt, and PlgBlt. PatBlt combines pixels in a rectangle in the destination DC with the brush selected into the device context, basically duplicating the subset of BitBlt raster operations that do not use a source DC. MaskBlt combines pixels in source and destination DCs and uses a monochrome bitmap as a mask. One raster operation (the "foreground" raster operation) is performed on pixels that correspond to 1s in the mask, and another raster operation (the "background" raster operation) is performed on pixels that correspond to 0s in the mask. PlgBlt blits a rectangular block of pixels in a source DC to a parallelogram in the destination DC and optionally Uses a monochrome bitmap as a mask during the transfer. Pixels That Correspond to 1S in the mask area blitted to the paralolelogram; Pixels That Correspond to 0s in the mask area, maskblt and p lgBlt are supported in Windows NT 3.1 and higher and in Windows 2000 but not in Windows 95 and Windows 98. If you call either of them in Windows 95 or Windows 98, you'll get a 0 return, indicating that the function failed.
Some output devices (notably plotters) do not support BitBlt and other blitting functions. To determine whether BitBlts are supported on a given device, get a device context and call GetDeviceCaps with a RASTERCAPS parameter. If the RC_BITBLT bit is set in the return value , the device supports BitBlts;. if the RC_STRETCHBLT bit is set, the device also supports StretchBlts There are no specific RASTERCAPS bits for other blit functions, but if you're writing for Windows NT and BitBlt is not supported, you should assume that PatBlt, MaskBlt, and PlgBlt are not supported, either. Generally, plotters and other vector-type devices that do not support blits will set the RC_NONE bit in the value returned by GetDeviceCaps to indicate that they do not support raster operations of Any Type.
BitBlt and other blitting functions produce the best results (and also perform the best) when the color characteristics of the source and destination DCs match. If you blit a 256-color bitmap to a 16-color destination DC, Windows must map the colors in the source DC to the colors in the destination DC. On some occasions, however, you can use color mapping to your advantage. When BitBlt blits a monochrome bitmap to a color DC, it converts 0 bits to the destination DC's current foreground color (CDC :: SetTextColor) and 1 bits to the destination DC's current background color (CDC :: SetBkColor). Conversely, when it blits a color bitmap to a monochrome DC, BitBlt converts pixels that match the destination DC's background color to 1 and all other pixels to 0. You can use the latter form of color mapping to create a monochrome mask from a color bitmap and use that mask in a routine that blits all pixels except those of a certain color from a bitmap to a screen DC, in effect creating transparent ? Pixels in the bitmap.Sound interesting Icons implement transparent pixels by storing two bitmaps for every icon image: a monochrome AND mask and a color XOR mask You can draw bitmaps with transparent pixels by writing an output routine that uses BitBlts and raster operations to. Build The and and xor masks on the fly. The Bitmapdemo Sample Program in The next section shows.
The bitmapdemo application
BitmapDemo is a non-document / view application created with AppWizard that demonstrates how to load a bitmap resource and BitBlt it to the screen. It also shows how to make clever use of BitBlts and raster-op codes to blit irregularly shaped images by designating one color in the bitmap as the transparency color. The program's output consists of a rectangular array of bitmap images drawn against a background that fades from blue to black. When Draw Opaque is checked in the Options menu, bitmaps are blitted to the screen unchanged, producing the result shown in Figure 15-5. If Draw Transparent is checked instead, red pixels are removed from the bitmaps when they're blitted to the screen. The result is pictured in Figure 15-6.Figure 15-5. The BitmapDemo window WITH Transparency Disabled.
Figure 15-6. The BitmapDemo Window with Transparency Enabled.
BitmapDemo uses a CBitmap-derived class named CMaskedBitmap to represent bitmaps CMaskedBitmap contains two member functions that CBitmap does not:. A Draw function for blitting a bitmap to a DC and a DrawTransparent function for blitting a bitmap to a DC and simultaneously filtering out all Pixels of a specified color. with cmaskedbitmap to lend a hand, The Statements
CmaskedBitmap Bitmap;
Bitmap.LoadBitmap (idb_bitmap);
Bitmap.draw (PDC, X, Y);
are all you need to create a bitmap object, load a bitmap resource into it, and draw that bitmap on the device represented by pDC. The x and y parameters specify the placement of the bitmap's upper left corner. The statements
CmaskedBitmap Bitmap;
Bitmap.LoadBitmap (idb_bitmap);
Bitmap.drawTransparent (PDC, X, Y, RGB (255, 0, 255));
do the same but do not blit any pixels in the bitmap whose color is bright magenta-RGB (255, 0, 255) With CMaskedBitmap to help out, drawing bitmaps with "holes" or nonrectangular profiles is easy:. just assign all the transparent pixels in the bitmap a common color and pass that color to DrawTransparent DrawTransparent will see to it that the transparent pixels do not get blitted along with the others.The source code for CMaskedBitmap :: Draw should look familiar to you:. it's identical to the DrawBitmap function discussed earlier. CMaskedBitmap :: DrawTransparent is a little more complicated. The comments in the source code should help you understand what's going on. If the comments do not make things clear enough, here's a summary of the steps involved in Blitting a bitmap to the screen omitting pixels of a certin color:
Create a memory DC, and select the bitmap into it. Create a second memory DC, and select in a monochrome bitmap whose size is identical to that of the original bitmap. Create an AND mask by setting the background color of the memory DC created in step 1 to the transparency color and blitting the bitmap to the DC. The resultant aND mask has 1s everywhere the original bitmap has pixels whose color equals the transparency color and 0s everywhere else. Create a third memory DC, and select in a bitmap whose size and color characteristics match those of the original bitmap. Create an XOR mask in this DC by first blitting the image from the memory DC created in step 1 to this DC with a SRCCOPY raster-op code and then blitting the aND mask to this DC with the raster-op code 0x220326. Create a fourth memory DC, and select in a bitmap whose size and color characteristics match those of the original bitmap. Blit the pixels from the rectangle in which the bitmap will go in the output DC to t he newly created memory DC. Create the final image in the memory DC created in step 4 by first blitting in the AND mask with a SRCAND raster-op code and then blitting in the XOR mask with a SRCINVERT raster-op code. Copy the image From The Memory DC to The Output DC.
Notice how BitBlt is used to generate the AND mask in step 2. Because the destination DC is monochrome, the GDI translates pixels whose color equals the background color to 1s and all other pixels to 0s at the destination. It's important to set the source DC's background color equal to the bitmap's transparency color first so. If you look at the code in CMaskedBitmap :: DrawTransparent that the transformation will be performed properly that corresponds to step 2, you'll see that the destination DC's size and color characteristics are set by using CBitmap :: CreateBitmap to create a monochrome bitmap whose dimensions equal the dimensions of the original bitmap and then selecting the monochrome bitmap into the DC. You control the size of a memory DC's display surface and the number of colors that it supports by selecting a Bitmap Into It. That's Why You See So Many Calls to createBitmap and createcompatiblebitmap in DrawTransparent.one Other Point of Interest in DrawTransparent Is The Raster -OP code 0x220326 Used in Step 3, Which Performs The Following Raster Operation Involving Pixels At The Source And Destination.
DEST = (Not SRC) And Dest
You can accomplish the same thing using "standard" raster-op codes by calling BitBlt twice: once with the raster-op code NOTSRCCOPY to invert the image in the source DC and again with SRCAND to AND the inverted image with the pixels in the destination DC. One BitBlt is obviously more efficient than two, but do not be surprised if the 0x220326 code does not perform any faster than the NOTSRCCOPY / SRCAND combination on some PCs. Most display drivers are optimized to perform certain raster operations faster than others , and it's always possible that a NOTSRCCOPY or a SRCAND will execute very quickly but a 0x220326 won't.As you experiment with BitmapDemo (whose source code appears in Figure 15-7), notice that the window takes longer to repaint when BitmapDemo draws transparent pixels. That's because DrawTransparent has to do a lot more work than Draw to get a single image to the screen. The worst performance hit occurs when DrawTransparent generates the same aND and XOR masks over and over ag ain. If you want the functionality of DrawTransparent in an application in which output performance is critical (for example, if you use transparent bitmaps to create spritelike objects that move about the screen), you should modify the CMaskedBitmap class so that the masks are generated just once and then reused as needed. Performance can also be improved by applying the aND and XOR masks directly to the destination DC rather than to a memory DC containing a copy of the pixels at the destination, but the small amount of flickering produced by the SHORT DELAY BETWEEN TOO MUCH INIMATION.
Figure 15-7. The bitmapdemo application.
Mainfrm.h // mainfrm.h: interface of the cmainframe class //
///
#if! defined (
AFX_MAINFRM_H__D71EF549_A6FE_11D2_8E53_006008A82731__included_)
#define AFX_MAINFRM_H__D71EF549_A6FE_11D2_8E53_006008A82731__included_
#iF _MSC_VER> 1000
#pragma overce
#ENDIF / / 100 m _ _ _
#include "childview.h"
Class CMAINFRAME: PUBLIC CFRAMEWND
{
PUBLIC:
CMAINFRAME ();
protected:
Declare_dynamic (CMAINFRAME)
// attributes
PUBLIC:
// Operations
PUBLIC:
// Overrides
// ClassWizard Generated Virtual Function Overrides
// {{AFX_VIRTUAL (CMAINFRAME)
Virtual Bool PrecreateWindow (CreateStruct & Cs);
Virtual Bool Oncmdmsg (uint Nid, Int Ncode, Void * Pextra,
AFX_CMDHANDLERINFO * PHANDLERINFO);
//}} AFX_VIRTUAL
// Implementation
PUBLIC:
Virtual ~ cmainframe ();
#ifdef _Debug
Virtual void assertvalid () const;
Virtual Void Dump (CDumpContext & DC) Const;
#ENDIF
protected: // control bar Embedded Member
CSTATUSBAR M_WNDSTATUSBAR;
CchildView M_WndView;
// generated message map functions
protected:
// {{AFX_MSG (CMAINFRAME)
AFX_MSG Int Oncreate (LPCReatestruct LPCreateStruct);
AFX_MSG Void OnsetFocus (CWND * PoldWnd);
AFX_MSG BOOL ONQUERYNEWPALETTE ();
AFX_MSG Void Onpalettechanged (CWND * PfocusWnd);
//}} AFX_MSG
Declare_message_map ()
}
///
// {{AFX_INSERT_LOCATION}}
// Microsoft Visual C Will Insert Additional Declarations
// Immediately Before The Previous Line.
#ENDIF
//! Defined (
// AFX_MAINFRM_H__D71EF549_A6FE_11D2_8E53_006008A82731__included_)
Mainfrm.cpp // mainfrm.cpp: importation of the cmainframe class
//
#include "stdafx.h"
#include "bitmapdemo.h"
#include "maskedbitmap.h"
#include "mainfrm.h"
#ifdef _Debug
#define new debug_new # undef this_file
Static char this_file [] = __file__;
#ENDIF
///
// CMAINFRAME
Implement_dynamic (CMAINFRAME, CFRAMEWND)
Begin_MESSAGE_MAP (CMAINFRAME, CFRAMEWND)
// {{AFX_MSG_MAP (CMAINFRAME)
ON_WM_CREATE ()
ON_WM_SETFOCUS ()
ON_WM_QUERYNEWPALETTE ()
ON_WM_PALETTECHANGED ()
//}} AFX_MSG_MAP
END_MESSAGE_MAP ()
Static uint indeicators [] =
{
ID_SEPARATOR
}
///
// CMAINFRAME CONSTRUCTION / DESTRUCTION
CMAINFRAME :: CMAINFRAME ()
{
}
CMAINFRAME :: ~ cmainframe ()
{
}
INT CMAINFRAME :: OnCreate (lpcreatestruct lpcreatestruct)
{
IF (cframewnd :: oncreate (lpcreatestruct) == -1)
Return -1;
// Create a view to occupy the client isa of the frame
IF (! m_wndview.create (null, null, afx_ws_default_view,
CRECT (0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL)
{
Trace0 ("Failed to Create View Window / N);
Return -1;
}
IF (! m_wndstatusbar.create (this) ||
M_WndStatusBar.setindicators (Indicators,
SIZEOF (INDICATORS) / SIZEOF (UINT))))
{
Trace0 ("Failed to Create Status Bar / N);
Return -1; // fail to create
}
Return 0;
}
Bool CMAINFRAME :: PrecreateWindow (CreateStruct & Cs)
{
IF (! cframeWnd :: PrecreateWindow (CS))
Return False;
// Todo: modify the window class or styles here by modifying
// The createStruct CS
Cs.dwexStyle & = ~ ws_ex_cliented;
cs.lpszclass = afxregisterWndclass (0);
Return True;
}
///
// CMAINFRAME DIAGNOSTICS
#ifdef _Debug
Void CMAINFRAME :: assertvalid () const
{
CframeWnd :: assertvalid ();
}
Void CMAINFRAME :: Dump (CDumpContext & DC) Const
{
CframeWnd :: DUMP (DC);
}
#ENDIF / / _ Debug
///
// CMAINFRAME MESSAGE HANDLERS
Void CMAINFRAME :: OnsetFocus (CWND * PoldWnd)
{
// forward focus to the view window
M_Wndview.Setfocus ();
}
Bool CMAINFRAME :: ONCMDMSG (Uint Nid, Int Ncode, Void * Pextra,
AFX_CMDHANDLERINFO * PHANDLERINFO)
{
// let The View Have First Crack At The Command
IF (M_WndView.oncmdmsg (NID, NCODE, PEXTRA, PHANDLERINFO))
Return True;
// OtherWise, Do Default Handling
Return CFrameWnd :: ONCMDMSG (NID, NCODE, PEXTRA, PHANDLERINFO);
}
Bool CMAINFRAME :: ONQUERYNEWPALETTE ()
{
m_wndview.invalidate ();
Return True;
}
Void CMAINFRAME :: OnPalettechanged (CWND * PFOCUSWND)
{
m_wndview.invalidate ();
}
Childview.h // childview.h: interface of the cchildview class
//
///
#if! defined (
AFX_CHILDVIEW_H__D71EF54B_A6FE_11D2_8E53_006008A82731__included_)
#define AFX_CHILDVIEW_H__D71EF54B_A6FE_11D2_8E53_006008A82731__included_
#iF _MSC_VER> 1000
#pragma overce
#ENDIF / / 100 m _ _ _
///
// cchildview window
Class Cchildview: Public CWND: PUBLIC CWND
{
// construction
PUBLIC:
CChildView ();
// attributes
PUBLIC:
// Operations
PUBLIC:
// Overrides
// ClassWizard Generated Virtual Function Overrides
// {{AFX_VIRTUAL (CCHildView)
protected:
Virtual Bool PrecreateWindow (CreateStruct & Cs);
//}} AFX_VIRTUAL
// Implementation
PUBLIC:
Virtual ~ cchildview ();
// generated message map functions
protected:
Void Dogradientfill (CDC * PDC, LPRECT Prect);
CPALETTE M_PALETTE;
CmaskedBitmap M_bitmap;
Bool m_bdrawopaque;
// {{AFX_MSG (CChildView)
AFX_MSG void onpaint ();
AFX_MSG Int Oncreate (LPCReatestruct LPCreateStruct);
AFX_MSG BOOL OneRaseBkGnd (CDC * PDC);
AFX_MSG void onOptionsDrawopaque ();
AFX_MSG void onOptionsdrawTransparent ();
AFX_MSG Void onupdateOptionsDrawopaque (CCMDUI * PCMDUI);
AFX_MSG Void onupdateOptionsDrawTransparent (ccmdui * pcmdui);
//}} AFX_MSG
Declare_message_map ()
}
///
// {{AFX_INSERT_LOCATION}}
// Microsoft Visual C Will Insert Additional Declarations // Immediately Before The Previous Line.
#ENDIF
//! Defined (
// AFX_CHILDVIEW_H__D71EF54B_A6FE_11D2_8E53_006008A82731__included_)
Childview.cpp // childview.cpp: Implementation of the cchildview class @ CLASS OF THE CCHILDVIEW CLASS
//
#include "stdafx.h"
#include "bitmapdemo.h"
#include "maskedbitmap.h"
#include "childview.h"
#ifdef _Debug
#define new debug_new
#undef this_file
Static char this_file [] = __file__;
#ENDIF
///
// cchildview
CChildview :: cchildview ()
{
m_bdrawopaque = true;
}
CchildView :: ~ cchildview ()
{
}
Begin_Message_Map (CchildView, CWND)
// {{AFX_MSG_MAP (cchildview)
ON_WM_PAINT ()
ON_WM_CREATE ()
ON_WM_ERASEBKGND ()
ON_COMMAND (id_options_draw_opaque, onOptionsDrawopaque)
ON_COMMAND (id_options_draw_transparent, onOptionsDrawTransparent)
ON_UPDATE_COMMAND_UI (ID_OPTIONS_DRAW_OPAQUE, ONUPDATEOPTIONSDRAWOPAQUE)
ON_UPDATE_COMMAND_UI (id_options_draw_transparent,
OnupdateOptionsDrawTransparent)
//}} AFX_MSG_MAP
END_MESSAGE_MAP ()
///
// Cchildview Message Handlers
Bool Cchildview :: PrecreateWindow (CreateStruct & Cs)
{
IF (! CWnd :: PrecreateWindow (CS))
Return False;
cs.dwexstyle | = WS_EX_CLIENTEDGE;
CS.Style & = ~ ws_border;
cs.lpszclass = AFXREGISTERWNDCLASS (CS_HREDRAW|CS_VREDREDREDRAW|CS_DBLCLKS,
:: LoadCursor (Null, Idc_arrow), Hbrush (Color_Window 1), NULL);
Return True;
}
void cchildview :: onpaint ()
{
CRECT RECT;
GetClientRect (& RECT);
CPAINTDC DC (this);
Bitmap BM;
M_bitmap.getbitmap (& BM);
INT CX = (Rect.width () / (BM.BMWIDTH 8)) 1;
INT CY = (Rect.Height () / (BM.BmHeight 8)) 1;
INT I, J, X, Y;
For (i = 0; i X = 8 (i * (BM.BMWIDTH 8); Y = 8 (j * (bm.bmheight 8); IF (m_bdrawopaque) M_bitmap.draw (& DC, X, Y); Else M_bitmap.drawtransparent (& DC, X, Y, RGB (255, 0, 0)); } } } Int cchildview :: oncreate (lpcreatestruct lpcreatestruct) { IF (cwnd :: oncreate (lpcreatestruct) == -1) Return -1; // // load the bitmap. // m_bitmap.loadbitmap (idb_bitmap); // // CREATE A PALETTE for A Gradient Fill IF this is a palettized device. // CClientDC DC (this); IF (DC.GetDeviceCaps (RasterCaps) & rc_palette) { Struct { Logpalette lp; Paletteentry APE [63]; } PAL; Logpalette * PLP = (logpalette *) & Pal; PLP-> paversion = 0x300; PLP-> PALNUMENTRIES = 64; For (int i = 0; i <64; i ) { PLP-> Palpalentry [i] .pered = 0; PLP-> Palpalentry [i] .pegreen = 0; PLP-> PALPALENTRY [I] .peblue = 255 - (i * 4); PLP-> Palpalent [I] .peflags = 0; } m_palette.createpalette (PLP); } Return 0; } Bool cchildview :: OneRaseBkGnd (CDC * PDC) { CRECT RECT; GetClientRect (& RECT); CPALETTE * POLDPALETTE; IF (HPALETTE) m_palette! = null) { Poldpalette = PDC-> SelectPalette (& M_Palette, False); PDC-> RealizePalette (); } DOGRADIENTFILL (PDC, & Re); IF ((HPALETTE) m_palette! = null) PDC-> SELECTPALETTE (POLDPALETTE, FALSE); Return True; } Void Cchildview :: DOGRADIENTFILL (CDC * PDC, LPRECT Prect) { CBRUSH * PBRUSH [64]; For (int i = 0; i <64; i ) PBRUSH [I] = New CBRUSH (Palettergb (0, 0, 255 - (i * 4))))) INT nwidth = prect-> Right - prect-> left; INT nheight = prect-> bottom - prect-> top; CRECT RECT; For (i = 0; i Rect.seTRECT (0, I, NWIDTH, I 1); PDC-> FillRect (& Rect, PBRUSH [(i * 63) / nHEight]); } For (i = 0; i <64; i ) Delete Pbrush [I]; } Void cchildview :: onOptionsDrawopaque () { m_bdrawopaque = true; Invalidate (); } Void cchildview :: onOptionsdrawTransparent () { m_bdrawopaque = false; Invalidate (); } Void cchildview :: onupdateOptionsdrawopaque (ccmdui * pcmdui) { PCMDUI-> SetCheck (m_bdrawopaque? 1: 0); } Void cchildview :: onupdateOptionsdrawTransparent (ccmdui * pcmdui) { PCMDUI-> SetCheck (m_bdrawopaque? 0: 1); } MaskedBitmap.h // maskedbitmap.h: interface for the cmaskedbitmap class. // // #if! defined ( AFX_MASKEDBITMAP_H__D71EF554_A6FE_11D2_8E53_006008A82731__included_) #define AFX_MASKEDBITMAP_H__D71EF554_A6FE_11D2_8E53_006008A82731__included_ #iF _MSC_VER> 1000 #pragma overce #ENDIF / / 100 m _ _ _ Class CMASKEDBITMAP: PUBLIC CBITMAP { PUBLIC: Void DrawTransparent (CDC * PDC, INT X, INT Y, ColorRef Clrtransparency; Void Draw (CDC * PDC, INT X, INT Y); } #ENDIF //! Defined ( // AFX_MASKEDBITMAP_H__D71EF554_A6FE_11D2_8E53_006008A82731__included_) MaskedBitMap.cpp // maskedbitmap.cpp: importation of the cmaskedbitmap class. // // #include "stdafx.h" #include "bitmapdemo.h" #include "maskedbitmap.h" #ifdef _Debug #undef this_file Static char this_file [] = __ file__; #define new debug_new #ENDIF Void cmaskedbitmap :: DRAW (CDC * PDC, INT X, INT Y) { Bitmap BM; GetBitmap (& BM); Cpoint size (BM.BMWIDTH, BM.BMHEIGHT); PDC-> DPTOLP (& size); CPOINT ORG (0, 0); PDC-> DPTOLP (& ORG); CDC DCMEM; DcMem.createCompatiPLEDC (PDC); CBITMAP * PoldbitMap = DCMem.selectObject (this); DcMem.SetMapMode (PDC-> getmapmode ()); PDC-> Bitblt (x, y, size.x, size.y, & dcmem, org.x, org.y, srcopy); DcMem.selectObject (Poldbitmap); } Void cmaskedbitmap :: DrawTransparent (cdc * pdc, int x, int y, ColorRef CLRTRANSPARENCY) { Bitmap BM; GetBitmap (& BM); Cpoint size (BM.BMWIDTH, BM.BMHEIGHT); PDC-> DPTOLP (& size); CPOINT ORG (0, 0); PDC-> DPTOLP (& ORG); // // CREATE A MEMORY DC (DCIMAGE) AND SELECT The Bitmap INTO IT. // CDC DCIMAGE; DCIMAGE.CREATECOMPALEDC (PDC); CBitmap * PoldbitMapImage = DCIMAGE.SELECTOBJECT (THIS); DCIMAGE.SETMAPMODE (PDC-> getmapmode ()); // // CREATE A Second Memory DC (DCAND) AND IN IT CREATE AN AND MASK. // CDC DCAN; Dcand.createCompaTibleDC (PDC); Dcand.setmapmode (PDC-> getmapmode ()); CBitmap Bitmapand; Bitmapand.createBitmap (BM.BMWIDTH, BM.BMHEIGHT, 1, 1, NULL); CBITMAP * PoldbitMapand = Dcand.selectObject (& Bitmapand); DCIMAGE.SETBKCOLOR (CLRTRANSPARENCY); Dcand.bitblt (Org.x, Org.y, Size.x, Size.y, & DCImage, Org.x, Org.y, Srccopy); // // Create A Third Memory DC (DCXOR) AND IN IT CREATE AN XOR MASK. // CDC DCXOR; DCXOR.CREATECOMPALEDC (PDC); DCXOR.SETMAPMODE (PDC-> getmapmode ()); CBitmap Bitmapxor; Bitmapxor.createCompabilityBitmap (& DCIMAGE, BM.BMWIDTH, BM.BMHEIGHT); CBITMAP * PoldbitMapxor = DCXOR.SelectObject (& Bitmapxor); DCXOR.BITBLT (Org.x, Org.y, Size.x, Size.y, & DCImage, Org.x, Org.y, Srccopy); DCXOR.BITBLT (ORG.X, Org.y, Size.x, size.y, & dcand, org.x, org.y, 0x220326); // // Copy The Pixels in The Destination Rectangle to a Temporary // Memory DC (DCTEMP). // CDC DCTEMP; DCTemp.createCompaTibleDC (PDC); DcTemp.SetmapMode (PDC-> getmapmode ()); cBitmap BitmapTemp; BitmapTemp.createCompablebitMap (& DCIMAGE, BM.BMWIDTH, BM.BMHEIGHT); CBITMAP * PoldbitMapTemp = DCTEMP.SELECTOBJECT (& BitmapTemp); DcTemp.bitblt (Org.x, Org.y, Size.x, Size.y, PDC, X, Y, Srccopy); // // generate the final image by applying the and and and xor masks to /////// The image in The Temporary Memory DC. // DcTemp.bitblt (Org.x, Org.y, Size.x, size.y, & dcand, org.x, org.y, Srcand); DcTemp.bitblt (Org.x, Org.y, Size.x, Size.y, & DCXOR, org.x, org.y, SRCINVERT); // // blit the resulting image to the screen. // PDC-> Bitblt (x, y, size.x, size.y, & dcTemp, org.x, org.y, srccopy); // // restore the default bitmaps. // DcTemp.selectObject (PoldbitmapTemp); DCXOR.SelectObject (PoldbitMapxor); Dcand.selectObject (PoldbitMapand); DCImage.selectObject (PoldbitmapImage); } Both Windows 98 and Windows 2000 support a new API function named :: TransparentBlt that performs the equivalent of a StretchBlt and also accepts a transparency color. Like BitmapDemo's DrawTransparent function, :: TransparentBlt skips pixels whose color equals the transparency color. I did not use :: TransparentBlt because I wanted BitmapDemo to work as well on down-level systems as it works on Windows 98 and Windows 2000 systems. Which of these transparency functions you should use depends on the platforms you're targeting. Writing a BMP File Viewer The disk-and-drive image drawn by BitmapDemo looks pretty good because it's a simple 16-color bitmap whose colors match the static colors in the system palette. As long as you draw the bitmaps yourself and stick to the colors in the default palette, bitmaps will display just fine without custom CPalettes. But if you write an application that reads arbitrary BMP files created by other programs and you rely on the default palette for color mapping, bitmaps containing 256 or more colors will be posterized-some rather severely. you can dramatically improve the quality of the output by creating a CPalette whose colors match the colors in the bitmap. The sample program in this section demonstrates how. It also shows one way that MFC programmers can combine CBitmaps with DIB sections to create more functional bitmaps. The Sample Program, Which I'll Call Vista, IS Shown In Figure 15-8. Vista IS A Document / View Bmp File Viewer That Will Read Virtually Any Bmp File Containing Any Number of Colors and draw a reasonable representation of it on a screen that's capable of displaying 256 or more colors. (Vista works with 16-color screens, too, but do not expect a lot from the output if the bitmap contains more than 16 colors.) The source code, selected portions of which appear in Figure 15-9, is surprisingly simple. Other than the code that creates a logical palette after a BMP file is read from disk, the application includes very little other than the standard stuff that forms the Core of Every Document / View Application. Figure 15-8. The Vista Window with a bitmap displayed. The view's OnDraw function displays bitmaps on the screen by selecting the logical palette associated with the bitmap into the device context (provided such a palette exists) and BitBlting the bitmap to a CScrollView. OnDraw retrieves the logical palette by calling the document's GetPalette function, and it retrieves the bitmap by calling the document's GetBitmap function. GetPalette returns a CPalette pointer to the palette that the document object creates when the bitmap is loaded. A NULL return means that no palette is associated with the bitmap, which in turn means that Vista is running on a nonpalettized video adapter. GetBitmap returns a pointer to the bitmap that constitutes the document itself. Vista's document class CVistaDoc stores the bitmap in a CBitmap data member named m_bitmap and the palette (if any) that goes with the bitmap in a CPalette member Named M_Palette. The Bitmap and Palette Objects Are Initialized When The Document's Onopendocument Function IS Called (WHEN T He User Selects Open from The File Menu) And Destroyed When The Document's DeleteContents Function IS CalledOcument Reads The Bmp File Named IN The Function's Parameter List: Hbitmap hbitmap = (hbitmap) :: loadimage (null, lpszpathname, Image_bitmap, 0, 0, lr_loadfromfile | lr_createdibsection; The value returned by :: LoadImage is a valid HBITMAP if the DIB section was successfully created and NULL if it was not. If :: LoadImage fails, it's highly likely that the file does not contain a DIB. OnOpenDocument indicates as much in the error message it displays when :: LoadImage returns NULL. If the HBITMAP is not NULL, OnOpenDocument attaches it to m_bitmap. The document (bitmap) is now loaded and ready to be displayed-almost.If Vista is running on a palettized display device, the bitmap probably will not look very good unless there's a logical palette to go with it. After :: LoadImage returns, OnOpenDocument grabs a device context and calls GetDeviceCaps to determine whether palettes are supported. If the return value does not contain An RC_PALETTE FLAG, ONOPENDOCUMENT RETURNS IMMEDIATELY AND Leaves m_palette uninitialized. Otherwise, onopendocument initializes m_palette with a logical Palette. To determine how best to create the palette, OnOpenDocument first finds out how many colors the bitmap contains by calling GetObject with a pointer to a DIBSECTION structure. One of the members of a DIBSECTION structure is a BITMAPINFOHEADER structure, and the BITMAPINFOHEADER structure's biClrUsed and biBitCount Fields Reveal The Number of Colors In The Bitmap. if BiClrused is Nonzero, IT Specifies The Color Count. if BiClrused is 0, The Number of Colors Equals 1 << Bibitcount The Following Code in Onopendocument Sets Ncolors Equal to the Numr of Colors in The Bitmap: Dibsection DS; M_bitmap.getObject (Sizeof (Dibsection), & DS); Int ncolors; IF (DS.DSBMIH.BICLRUSED! = 0) Ncolors = ds.dsbmih.biclrused; Else Ncolors = 1 << DS.DSBMIH.BIBITCOTINT; What OnOpenDocument does next depends on the value of nColors. If nColors is greater than 256, indicating that the bitmap has a color depth of 16, 24, or 32 bits (images stored in BMP files always use 1-bit, 4-bit, 8-bit, 16-bit, 24-bit, or 32-bit color, onopendocument creates a Halftone Palette by calling cpalette :: CreatehalftonePalette with a pointer to the screen dc it obtained earlier: if (ncolors> 256) m_palette.createhalftonePalette (& DC); In return, the system creates a generic palette with a rainbow of colors that's suited to the device context. In most cases, a logical palette created by CreateHalftonePalette will contain 256 colors. That's not enough to allow a bitmap containing thousands or perhaps millions of colors To be displayed with 100 Percent Accuracy, But it will produme the get... If nColors is less than or equal to 256, OnOpenDocument initializes m_palette with a logical palette whose colors match the colors in the bitmap. The key to matching the bitmap's colors is the API function :: GetDIBColorTable, which copies the color table associated with a 1 -bit, 4-bit, or 8-bit dibquad structures. That Array, In Turn, IS Used to Initialize ARRAY OF PALETTEENTRY STRUCTURES AND CREATE A LOGICAL PALETTE: RGBQUAD * prg = new rgbquad [ncolors]; CDC MEMDC; Memdc.createCompatibleDC (& DC); CBitmap * PoldbitMap = MEMDC.SELECTOBJECT (& M_Bitmap); :: GetDibcolortable ((HDC) MEMDC, 0, NCOLORS, PRGB); MEMDC.SELECTOBJECT (POLDBITMAP); Uint nsize = sizeof (logpalette) (SIZEOF (PALETTEENTRY) * (NCOLORS - 1)); Logpalette * PLP = (logpalette *) New byte [nsize]; PLP-> paversion = 0x300; PLP-> PALNUMENTRIES = NCOLORS; For (int I = 0; i PLP-> Palpalentry [i] .pered = prg [i] .rgbred; PLP-> Palpalentry [i] .pegreen = prg [i] .rgbgreen; PLP-> Palpalentry [i] .peblue = prg [i] .rgbblue; PLP-> Palpalent [I] .peflags = 0; } m_palette.createpalette (PLP); :: GetDIBColorTable works only if the DIB section is selected into a device context, so OnOpenDocument creates a memory DC and selects m_bitmap into it before making the call The rest is just detail:. Allocating memory for a LOGPALETTE structure, transferring the RGBQUAD values from . For a nice touch, Vista includes a readout in its status bar that identifies the bitmap's dimensions and color depth (bits per pixel). The status bar is updated when OnOpenDocument sends Vista's main window a WM_USER_UPDATE_STATS message containing a pointer to the string that it wants To Appear in The Status Bar Pane. A Message Handler In The Frame Window Class Fields The Message and Updates The Status Bar Accordingly. Figure 15-9. The Vista Application. Mainfrm.h // mainfrm.h: interface of the cmainframe class // /// #if! defined ( AFX_MAINFRM_H__3597FEA9_A70E_11D2_8E53_006008A82731__included_) #define AFX_MAINFRM_H__3597FEA9_A70E_11D2_8E53_006008A82731__included_ #iF _MSC_VER> 1000 #pragma overce #ENDIF / / 100 m _ _ _ Class CMAINFRAME: PUBLIC CFRAMEWND { protected: // Create from Serialization Only CMAINFRAME (); Declare_DyncReate (CMAINFRAME) // attributespublic: // Operations PUBLIC: // Overrides // ClassWizard Generated Virtual Function Overrides // {{AFX_VIRTUAL (CMAINFRAME) Virtual Bool PrecreateWindow (CreateStruct & Cs); //}} AFX_VIRTUAL // Implementation PUBLIC: Virtual ~ cmainframe (); #ifdef _Debug Virtual void assertvalid () const; Virtual Void Dump (CDumpContext & DC) Const; #ENDIF protected: // control bar Embedded Member CSTATUSBAR M_WNDSTATUSBAR; // generated message map functions protected: // {{AFX_MSG (CMAINFRAME) AFX_MSG Int Oncreate (LPCReatestruct LPCreateStruct); AFX_MSG BOOL ONQUERYNEWPALETTE (); AFX_MSG Void Onpalettechanged (CWND * PfocusWnd); //}} AFX_MSG AFX_MSG LRESULT OnUpdateImagestats (WPARAM WPARAM, LPARAM LPARAM); Declare_message_map () } /// // {{AFX_INSERT_LOCATION}} // Microsoft Visual C Will Insert Additional Declarations // Immediately Before The Previous Line. #ENDIF //! Defined (AFX_MAINFRM_H__3597FEA9_A70E_11D2_8E53_006008A82731__INCluded_) Mainfrm.cpp // mainfrm.cpp: importation of the cmainframe class // #include "stdafx.h" #include "vista.h" #include "mainfrm.h" #ifdef _Debug #define new debug_new #undef this_file Static char this_file [] = __file__; #ENDIF /// // CMAINFRAME Implement_dyncreate (CMAINFRAME, CFRAMEWND) Begin_MESSAGE_MAP (CMAINFRAME, CFRAMEWND) // {{AFX_MSG_MAP (CMAINFRAME) ON_WM_CREATE () ON_WM_QUERYNEWPALETTE () ON_WM_PALETTECHANGED () //}} AFX_MSG_MAP ON_MESSAGE (WM_USER_UPDATE_STATS, ONUPDATEIMAGESTATS) END_MESSAGE_MAP () Static uint indeicators [] = { ID_separator, ID_SEPARATOR } /// // CMAINFRAME CONSTRUCTION / DESTRUCTION CMAINFRAME :: CMAINFRAME () { } CMAINFRAME :: ~ cmainframe () { } INT CMAINFRAME :: OnCreate (lpcreatestruct lpcreatestruct) { IF (cframewnd :: oncreate (lpcreatestruct) == -1) Return -1; // // Create The Status Bar. // IF (! m_wndstatusbar.create (this) || M_WndStatusBar.setindicators (Indicators, SIZEOF (INDICATORS) / SIZEOF (UINT)))) { Trace0 ("Failed to Create Status Bar / N); Return -1; // fail to create } // // Size The Status Bar's Rightmost Pane to Hold A Text String. // TextMetric TM; CClientDC DC (this); CFont * pfont = m_wndstatusbar.getfont (); CFont * PoldFont = Dc.selectObject (PFont); Dc.getTextMetrics; & TM); Dc.selectObject (PoldFont); Int cxwidth; UINT NID, NStyle; M_WndStatusBar.getPaneInfo (1, NID, NStyle, CXWIDTH); CXWIDTH = Tm.tmavecharWidth * 24; M_WndStatusBar.SetPaneInfo (1, NID, NStyle, CXWIDTH); Return 0; } Bool CMAINFRAME :: PrecreateWindow (CreateStruct & Cs) { IF (! cframeWnd :: PrecreateWindow (CS)) Return False; Return True; } /// // CMAINFRAME DIAGNOSTICS #ifdef _Debug Void CMAINFRAME :: assertvalid () const { CframeWnd :: assertvalid (); } Void CMAINFRAME :: Dump (CDumpContext & DC) Const { CframeWnd :: DUMP (DC); } #ENDIF / / _ Debug /// // CMAINFRAME MESSAGE HANDLERS Bool CMAINFRAME :: ONQUERYNEWPALETTE () { CDocument * pdoc = getActiveDocument (); IF (PDOC! = NULL) GetActiveDocument () -> UpdateAllViews (NULL); Return True; } Void CMAINFRAME :: OnPalettechanged (CWND * PFOCUSWND) { IF (pfocusWnd! = this) { CDocument * pdoc = getActiveDocument (); IF (PDOC! = NULL) GetActiveDocument () -> UpdateAllViews (NULL); } } Lresult CMAINFRAME :: OnUpdateImagestats (WPARAM WPARAM, LPARAM LPARAM) { M_WndStatusBar.SetPanetext (1, (lpctstr) lparam, true); Return 0; } Vistadoc.h // Vistadoc.h: interface of the cvistadoc class // /// #if! defined ( AFX_VISTADOC_H__3597FEAB_A70E_11D2_8E53_006008A82731__included_) #define AFX_VISTADOC_H__3597FEAB_A70E_11D2_8E53_006008A82731__included_ #iF _MSC_VER> 1000 #pragma overce #ENDIF / / 100 m _ _ _ Class Cvistadoc: Public CDocument { protected: // Create from Serialization Only Cvistadoc (); Declare_Dyncreate (Cvistadoc) // attributes PUBLIC: // Operations PUBLIC: // Overrides // ClassWizard Generated Virtual Function Overrides // {{AFX_VIRTUAL (CVistAdoc) PUBLIC: Virtual bool onnewdocument (); Virtual Void Serialize (CARCHIVE & A); Virtual Bool Onopendocument (LPCTSTR LPSZPATHNAME); Virtual void deleteContents (); //}} AFX_VIRTUAL // Implementation PUBLIC: CPALETTE * GETPALETTE (); CBITMAP * getBitmap (); Virtual ~ cvistadoc (); #ifdef _Debug Virtual void assertvalid () const; Virtual Void Dump (CDumpContext & DC) Const; #ENDIF protected: // generated message map functions protected: CPALETTE M_PALETTE; CBITMAP M_BITMAP; // {{AFX_MSG (cvistadoc) // Note - The ClassWizard Will Add and Remove Member functions here. // Do Not Edit What You See in these Blocks of generated code! //}} AFX_MSG Declare_message_map () } /// // {{AFX_INSERT_LOCATION}} // Microsoft Visual C Will Insert Additional Declarations // Immediately Before The Previous Line. #ENDIF //! Defined ( // AFX_VISTADOC_H__3597FEAB_A70E_11D2_8E53_006008A82731__included_) Vistadoc.cpp // Vistadoc.cpp: Implementation of the cvistadoc class // #include "stdafx.h" #include "vista.h" #include "vistadoc.h" #ifdef _Debug #define new debug_new #undef this_file Static char this_file [] = __file__; #endif /// // cvistadoc Implement_dyncreate (cvistadoc, cdocument) Begin_MESSAGE_MAP (Cvistadoc, CDocument) // {{AFX_MSG_MAP (Cvistadoc) // Note - The Classwizard Will Add and Remove Mapping Macros Here. // Do Not Edit What You See in these Blocks of generated code! //}} AFX_MSG_MAP END_MESSAGE_MAP () /// // cvistadoc construction / destruction Cvistadoc :: cvistadoc () { } Cvistadoc :: ~ cvistadoc () { } Bool cvistadoc :: onnewdocument () { IF (! cdocument :: onnewdocument ()) Return False; Return True; } /// // cvistadoc serialization Void Cvistadoc :: Serialize (CARCHIVE & A) { IF (ar.isstoring ()) { // Todo: Add Storing Code Here } Else { // Todo: add loading code here } } /// // Cvistadoc Diagnostics #ifdef _Debug Void cvistadoc :: assertvalid () const { CDocument :: assertvalid (); } Void Cvistadoc :: Dump (CDumpContext & DC) Const { CDocument :: DUMP (DC); } #ENDIF / / _ Debug /// // Cvistadoc Commands Bool cvistadoc :: onopendocument (lpctstr lpszpathname) { IF (! cdocument :: onopendocument (lpszpathname)) Return False; // // Open the file and create a dib section from its contents. // Hbitmap hbitmap = (hbitmap) :: loadimage (null, lpszpathname, Image_bitmap, 0, 0, lr_loadfromfile | lr_createdibsection; IF (hbitmap == null) { CString string; String.Format (_T ("% s does not contain a dib"), lpszpathname); AfxMessageBox (String); Return False; } m_bitmap.attach (hbitmap); // // Return Now if this Device Doesn't Support Palettes. // CClientDC DC (NULL); IF ((DC.GetDeviceCaps (RasterCaps) & rc_palette) == 0) Return True; // // Create a Palette to go with the dib section. // IF ((hbitmap) m_bitmap! = null) { Dibsection DS; M_bitmap.getObject (Sizeof (Dibsection), & DS); int Ncolors; IF (DS.DSBMIH.BICLRUSED! = 0) Ncolors = ds.dsbmih.biclrused; Else Ncolors = 1 << DS.DSBMIH.BIBITCOTINT; // // Create a Halftone Palette if The Dib Section Contains More // Than 256 colors. // IF (ncolors> 256) m_palette.createhalftonePalette (& DC); // // Create a Custom Palette From The Dib Section's Color Table // if The number of colors is 256 or less. // Else { RGBQUAD * prg = new rgbquad [ncolors]; CDC MEMDC; Memdc.createCompatibleDC (& DC); CBitmap * PoldbitMap = MEMDC.SELECTOBJECT (& M_Bitmap); :: GetDibcolortable ((HDC) MEMDC, 0, NCOLORS, PRGB); MEMDC.SELECTOBJECT (POLDBITMAP); Uint nsize = sizeof (logpalette) (SIZEOF (PALETTEENTRY) * (NCOLORS - 1)); Logpalette * PLP = (logpalette *) New byte [nsize]; PLP-> paversion = 0x300; PLP-> PALNUMENTRIES = NCOLORS; For (int I = 0; i PLP-> Palpalentry [i] .pered = prg [i] .rgbred; PLP-> Palpalentry [i] .pegreen = prg [i] .rgbgreen; PLP-> Palpalentry [i] .peblue = prg [i] .rgbblue; PLP-> Palpalent [I] .peflags = 0; } m_palette.createpalette (PLP); DELETE [] PLP; delete [] prgb; } } Return True; } Void Cvistadoc :: deleteContents () { IF ((hbitmap) m_bitmap! = null) m_bitmap.deleteObject (); IF ((HPALETTE) m_palette! = null) m_palette.deleteObject (); CDocument :: deleteContents (); } CBitmap * cvistadoc :: getBitmap () { Return ((hbitmap) m_bitmap == null)? NULL: & m_bitmap; } CPALETTE * CVISTADOC :: getPalette () { Return (HPALETTE) m_palette == null)? NULL: & M_Palette; } VistaView.h // Vistaview.h: interface of the cvistaview class // /// #if! defined ( AFX_VISTAVIEW_H__3597FEAD_A70E_11D2_8E53_006008A82731__included_) #define AFX_VISTAVIEW_H__3597FEAD_A70E_11D2_8E53_006008A82731__included_ #iF _MSC_VER> 1000 #pragma overce #ENDIF / / 100 m _ _ _ Class CvistaView: Public CscrollVIew { protected: // Create from Serialization Only Cvistaview (); Declare_DyncReate (CVistaView) // attributes PUBLIC: Cvistadoc * getDocument (); // Operations PUBLIC: // Overrides // ClassWizard Generated Virtual Function Overrides // {{AFX_VIRTUAL (CVISTAVIEW) PUBLIC: Virtual void OnDraw (CDC * PDC); // Overridden to Draw this View Virtual Bool PrecreateWindow (CreateStruct & Cs); protected: Virtual void OnInitialUpdate (); // Called First Time After Construct //}} AFX_VIRTUAL // Implementation PUBLIC: Virtual ~ cvistaview (); #ifdef _Debug Virtual void assertvalid () const; Virtual Void Dump (CDumpContext & DC) Const; #ENDIF protected: // generated message map functions protected: // {{AFX_MSG (CVistaView) // Note - The ClassWizard Will Add and Remove Member functions here. // Do Not Edit What You See in these Blocks of generated code! //}} AFX_MSG Declare_message_map () } #ifndef _debug // debug version in vistaView.cpp Inline cvistadoc * cvistaview :: getDocument () {Return (cvistadoc *) m_pdocument; #ENDIF /// // {{AFX_INSERT_LOCATION}} // Microsoft Visual C Will Insert Additional Declarations // Immediately Before The Previous Line. #ENDIF //! Defined ( // AFX_VISTAVIEW_H__3597FEAD_A70E_11D2_8E53_006008A82731__included_) VistaView.cpp // VistaView.cpp: Implementation of The CvistaView Class // #include "stdafx.h" #include "vista.h" #include "vistadoc.h" #include "vistaview.h" #ifdef _Debug #define new debug_new #undef this_file Static char this_file [] = __file__; #ENDIF /// // CvistaView Implement_dyncreate (CvistaView, CScrollView) Begin_MESSAGE_MAP (CvistaView, CScrollView) // {{AFX_MSG_MAP (CVistaView) // Note - The Classwizard Will Add and Remove Mapping Macros Here. // Do Not Edit What You See in these Blocks of generated code! //}} AFX_MSG_MAP END_MESSAGE_MAP () /// // CvistaView Construction / Destruction Cvistaview :: cvistaview () { } CvistaView :: ~ cvistaview () { } Bool CvistaView :: PrecreateWindow (CreateStruct & Cs) { Return CscrollView :: PrecreateWindow (CS); } /// // CvistaView Drawing Void Cvistaview :: OnDraw (CDC * PDC) { Cvistadoc * pdoc = getDocument (); Ask_VALID (PDOC); CBITMAP * PBITMAP = PDOC-> getBitmap (); IF (pbitmap! = null) { CPALETTE * POLDPALETTE; CPALETTE * PPALETTE = PDOC-> getPalette (); IF (PPALETTE! = null) { Poldpalette = PDC-> SelectPalette (PPALETTE, FALSE); PDC-> RealizePalette (); } Dibsection DS; Pbitmap-> GetObject (Sizeof (Dibsection), & DS CDC MEMDC; MEMDC.CREATECOMPALEDC (PDC); CBITMAP * PoldbitMap = MEMDC.SELECTOBJECT (PBITMAP); PDC-> Bitblt (0, 0, DS.DSBM.BMWIDTH, DS.DSBM.BMHEIGHT, & MEMDC, 0, 0, SRCCOPY; MEMDC.SELECTOBJECT (POLDBITMAP); IF (PPALETTE! = NULL) PDC-> SELECTPALETTE (POLDPALETTE, FALSE); } } Void cvistaview :: onInitialupdate () { CscrollView :: OnInitialupdate (); CString string; CSIZE SIZETAl; CBitmap * pbitmap = getDocument () -> getBitmap (); // // if a bitmap is loading, set the view size equal to the bitmap size. // Otherwise, set the view's width and height to 0.// IF (pbitmap! = null) { Dibsection DS; Pbitmap-> GetObject (Sizeof (Dibsection), & DS Siz.dsbm.bmwidth; Siz.dsbm.bmheight; String.Format (_T ("/ T% D x% D,% D bpp"), ds.dsbm.bmwidth, DS.DSBM.BMHEIGHT, DS.DSBMIH.BIBITCOTINT } Else { Sizetotal.cx = sizetotal.cy = 0; String.empty (); } AfxgetMainWnd () -> SendMessage (WM_USER_UPDATE_STATS, 0, (LParam) (LPCTSTR) String; Setscrollsizes (mm_text, sizetotal); } /// // CvistaView Diagnostics #ifdef _Debug Void Cvistaview :: assertvalid () const { CscrollView :: assertvalid (); } Void Cvistaview :: Dump (CDumpContext & DC) Const { CscrollView :: DUMP (DC); } Cvistadoc * cvistairs :: getDocument () // non-debug version is inline { Assert (m_pdocument-> iskindof (runtime_class (cvistadoc)); Return (cvistadoc *) m_pdocument; } #ENDIF / / _ Debug /// // CvistaView Message Handlers More on the :: loadImage function One Reason Vista Can Do So Much with So Little Code Is That The: LoadImage Function Allows A Dib Section To Be Built from A Bmp File with Just One Statement. Here's That Statement Again: Hbitmap hbitmap = (hbitmap) :: loadimage (null, lpszpathname, Image_bitmap, 0, 0, lr_loadfromfile | lr_createdibsection; :: LoadImage is to DIB sections what :: LoadBitmap and CDC :: LoadBitmap are to DDBs. But it's also much more. I will not rehash all the input values it accepts because you can get that from the documentation, but here's a short Summary of some of the things you can do with :: loadimage: Load bitmap resources, and create DDBs and DIB sections from them. Load bitmaps stored in BMP files, and create DDBs and DIB sections from them. Automatically convert three shades of gray (RGB (128, 128, 128), RGB (192, 192 , 192), and RGB (223, 223, 223)) to the system colors COLOR_3DSHADOW, COLOR_3DFACE, and COLOR_3DLIGHT as an image is loaded. Automatically convert the color of the pixel in the upper left corner of the bitmap to the system color COLOR_WINDOW or COLOR_3DFACE so that the pixel and others like it will be invisible against a COLOR_WINDOW or COLOR_3DFACE background. Convert a color image to monochrome.Keep in mind that :: LoadImage's color-mapping capabilities work only with images that contain 256 or fewer colors. DIBs with 256 or fewer colors contain built-in color tables that make color mapping fast and efficient. Rather than examine every pixel in the image to perform a color conversion, :: LoadImage simply modifies the color table. Vista demonstrates how :: LoadImage can be used to create a DIB section from a BMP file and attach it to a CBitmap object. One advantage of loading a bitmap as a DIB section instead of as an ordinary DDB is that you can call functions such as :: GetDIBColorTable on it. Had the LR_CREATEDIBSECTION flag been omitted from the call to :: LoadImage, we would have been unable to access the bitmap's color table and create a logical palette from it. In general, your applications will port more easily to future Versions of Windows (and probably Perform Better, TOO) IF You Now Start Using Dib Sections INSTEAD OF DDBS WHENEVER POSSIBLE.