In-memory HBITMAP

One day, i needed to accomply a weird(?) operation: modify a bitmap "in memory" and create a copy for my purposes, e.g. resizing it..

HBITMAP ResizeBmp(HWND hWnd,HBITMAP hBmp,int cx,int cy)
{
    HDC dc =GetDC(hWnd);
    HDC copyDC = CreateCompatibleDC(dc);
    HDC srcDC = CreateCompatibleDC(dc);
    int oriCx,oriCy;

    //Get Original Size
    BITMAP bm;
    GetObject(hBmp, sizeof(bm),&bm);
    oriCx = bm.bmWidth;
    oriCy = bm.bmHeight;

    RECT bmpRect;
    bmpRect.top=0;
    bmpRect.left=0;
    bmpRect.right=cx;
    bmpRect.bottom=cy;

    RECT oriRect = bmpRect;
    oriRect.right=oriCx;
    oriRect.bottom=oriCy;

    HRGN rgn1 = CreateRectRgnIndirect( &bmpRect );
    HRGN rgn2 = CreateRectRgnIndirect( &oriRect );
    SelectClipRgn(copyDC,rgn1);
    SelectClipRgn(srcDC,rgn2);
    DeleteObject(rgn1);
    DeleteObject(rgn2);

    HBITMAP copyBMP = CreateCompatibleBitmap(dc,cx,cy);
    HBITMAP copyBMPold = (HBITMAP)SelectObject(copyDC,copyBMP);
    HBITMAP srcBMPold = (HBITMAP)SelectObject(srcDC,hBmp);

    if(oriCx!=cx || oriCy!=cy){
        StretchBlt(copyDC,0,0,cx,cy,srcDC,0,0,oriCx,oriCy,SRCCOPY);
    }else{
        BitBlt(copyDC,0,0,cx,cy,srcDC,0,0,SRCCOPY);
    }

    copyBMP = (HBITMAP)SelectObject(copyDC, copyBMPold);

    DeleteDC(copyDC);
    DeleteDC(srcDC);

    return copyBMP;
}

Or resize it with a mask

HBITMAP ResizeBmpMask(HWND hWnd,HBITMAP hBmp,int cx,int cy,COLORREF clColor)
{
    HDC dc =GetDC(hWnd);
    HDC copyDC = CreateCompatibleDC(dc);
    HDC srcDC = CreateCompatibleDC(dc);
    HDC maskDC = CreateCompatibleDC(dc);
    int oriCx,oriCy;

    //Get Original Size
    BITMAP bm;
    GetObject(hBmp, sizeof(bm),&bm);
    oriCx = bm.bmWidth;
    oriCy = bm.bmHeight;

    RECT bmpRect;
    bmpRect.top=0;
    bmpRect.left=0;
    bmpRect.right=cx;
    bmpRect.bottom=cy;

    RECT oriRect = bmpRect;
    oriRect.right=oriCx;
    oriRect.bottom=oriCy;

    HBITMAP maskBmp = GetBmpMask(hWnd,hBmp,cx,cy);
    HBITMAP sizedBmp = ResizeBmp(hWnd,hBmp,cx,cy);

    HRGN rgn1 = CreateRectRgnIndirect( &bmpRect );
    HRGN rgn2 = CreateRectRgnIndirect( &bmpRect );
    HRGN rgn3 = CreateRectRgnIndirect( &bmpRect );
    SelectClipRgn(copyDC,rgn1);
    SelectClipRgn(srcDC,rgn2);
    SelectClipRgn(maskDC,rgn3);
    DeleteObject(rgn1);
    DeleteObject(rgn2);
    DeleteObject(rgn3);

    HBITMAP copyBMP = CreateCompatibleBitmap(dc,cx,cy);
    HBITMAP copyBMPold = (HBITMAP)SelectObject(copyDC,copyBMP);
    HBITMAP srcBMPold = (HBITMAP)SelectObject(srcDC,sizedBmp);
    HBITMAP maskBMPold = (HBITMAP)SelectObject(maskDC,maskBmp);

    FillRect(copyDC,&oriRect,CreateSolidBrush(clColor));

    COLORREF clTransparent = GetPixel(srcDC,0,0);
    TransparentBlt(copyDC,0,0,cx,cy,srcDC,0,0,cx,cy,(UINT)clTransparent);

    copyBMP = (HBITMAP)SelectObject(copyDC, copyBMPold);

    DeleteDC(copyDC);
    DeleteDC(srcDC);

    return copyBMP;
}

Last modified on: May 02, 2003