Scaling 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 enables the 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; 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 as shown in the following table.

Stretch Mode Method
BLACKONWHITE Performs a logical AND operation on the color data for the eliminated pixels and the color data for the remaining pixels.
WHITEONBLACK Performs a logical OR operation on the color data for the eliminated pixels and the color data for the remaining pixels.
COLORONCOLOR Eliminates the color data of the deleted pixels completely.
HALFTONE Approximates the original (source) color data in the destination.

You set the stretch mode by calling the SetStretchBltMode function.

The following example 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;