Copying a bitmap from another HBITMAP
Asked Answered
M

2

6

I'm trying to write a class to wrap bitmap functionality in my program.

One useful feature would be to copy a bitmap from another bitmap handle. I'm a bit stuck:

    void operator=( MyBitmapType & bmp )
    {
        HDC dcMem;
        HDC dcSource;

        if( m_hBitmap != bmp.Handle() )
        {
            if( m_hBitmap )             
                this->DisposeOf();

            // copy the bitmap header from the source bitmap
            GetObject( bmp.Handle(), sizeof(BITMAP), (LPVOID)&m_bmpHeader );

            // Create a compatible bitmap
            dcMem       = CreateCompatibleDC( NULL );
            m_hBitmap   = CreateCompatibleBitmap( dcMem, m_bmpHeader.bmWidth, m_bmpHeader.bmHeight );

            // copy bitmap data
            BitBlt( dcMem, 0, 0, bmp.Header().bmWidth, bmp.Header().bmHeight, dcSource, 0, 0, SRCCOPY );
        }
    }

This code is missing one thing: How can I get an HDC to the source bitmap if all I have of the source bitmap is a handle (e.g. an HBITMAP?)

You can see in the code above, I've used "dcSource" in the BitBlt() call. But I don't know how to get this dcSource from the source bitmap's handle (bmp.Handle() returns the source bitmaps handle)

Mathematical answered 16/4, 2011 at 14:45 Comment(0)
G
11

You can't -- the source bitmap may not be selected into a DC at all, and even if it is you have no way to find out what DC.

To do your copy, you probably want to use something like:

dcSrc = CreateCompatibleDC(NULL);
SelectObject(dcSrc, bmp);

Then you can blit from the source to destination DC.

Gluteus answered 16/4, 2011 at 15:16 Comment(0)
S
8

Worked for me:

// hBmp is a HBITMAP 
HBITMAP hBmpCopy= (HBITMAP) CopyImage(hBmp, IMAGE_BITMAP, 0, 0, LR_DEFAULTSIZE);
Shermy answered 28/7, 2017 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.