63.2.2 Using a Bitmap to Scale an Image

Some applications scale images (that is, they display “zoomed” or “reduced” views of an image). For example, a drawing application may provide a “zoom” feature that allows a user to view and edit a drawing on a pixel-by-pixel basis.

Applications scale images by calling the StretchBlt function. Like the BitBlt function, StretchBlt copies bitmap data from a bitmap in a source DC into a bitmap in a target DC. However, unlike the BitBlt function, StretchBlt scales the image based on the specified dimensions of the source and target rectangles. If the source rectangle is larger than the target rectangle, the resultant image will appear to have shrunk; and, if the source rectangle is smaller than the target rectangle, the resultant image will appear to have expanded.

If the target rectangle is smaller than the source rectangle, StretchBlt removes color data from the image according to a specified stretch-mode. The default StretchBlt mode (BLACKONWHITE) performs a logical AND operation on the color-data for eliminated pixels with the color-data for remaining pixels. The three other stretch-modes combine the color-data by performing a logical OR operation, by completely eliminating the color-data of deleted pixels, or by approximating the original (source) color-data in the destination. You can set the stretch-mode by calling the SetStretchBltMode function.

The following code is taken from an application that displays an image either at its original size or a twice the original size. (This application uses the default stretch mode.):

hdcScaled = CreateCompatibleDC(hdcScreen);

hbmScaled = CreateCompatibleBitmap(hdcScreen,

GetDeviceCaps(hdcScreen, HORZRES) * 2,

GetDeviceCaps(hdcScreen, VERTRES) * 2);

if (hbmScaled == 0)

errhandler("hbmScaled", hwnd);

/* Select the bitmaps into the compatible DC. */

if (!SelectObject(hdcScaled, hbmScaled))

errhandler("Scaled Bitmap Selection", hwnd);

case WM_COMMAND: /* message: command from application menu */

switch(wParam) {

case IDM_SCALEX1:

if (fBlt){

fScaled = FALSE;

hdcWin = GetDC(hwnd);

BitBlt(hdcWin,

0,0,

bmp.bmWidth, bmp.bmHeight,

hdcCompatible,

0,0,

SRCCOPY);

ReleaseDC(hwnd, hdcWin);

}

break;

case IDM_SCALEX2:

if (fBlt){

fScaled = TRUE;

StretchBlt(hdcScaled,

0, 0,

bmp.bmWidth * 2, bmp.bmHeight * 2,

hdcCompatible,

0, 0,

bmp.bmWidth, bmp.bmHeight,

SRCCOPY);

hdcWin = GetDC(hwnd);

BitBlt(hdcWin,

0,0,

bmp.bmWidth, bmp.bmHeight,

hdcScaled,

0,0,

SRCCOPY);

ReleaseDC(hwnd, hdcWin);

}

break;