views:

69

answers:

4

Hi,

I want to create a crop function in an existing engine. This is what I already have:

bool Bitmap::Crop(RECT cropArea)
{
BITMAP bm;
GetObject(m_Handle, sizeof(bm), &bm);

HDC hSrc = CreateCompatibleDC(NULL);
SelectObject(hSrc, m_Handle);

HDC hNew = CreateCompatibleDC(NULL);
HBITMAP hBmp = CreateCompatibleBitmap(hNew, bm.bmWidth, bm.bmHeight);
HBITMAP hOld = (HBITMAP)SelectObject(hNew, hBmp);

BitBlt(hNew, 0, 0, bm.bmWidth, bm.bmHeight, hSrc, 0, 0, SRCCOPY);

SelectObject(hNew, hOld);

DeleteDC(hSrc);
DeleteDC(hNew);

DeleteObject(m_Handle);

m_Handle = hBmp;
}

I want it to just copy the whole image to a new HBITMAP and replace the old with it. So I know that it works. After that it is just playing with the BitBlt parameters.

m_Handle is a HBITMAP of the class Bitmap.

The result of this code is just a black screen.

A: 

And your question is?

Frederik Slijkerman
Oops, forgot the real question sorry about that.It does not work.I only get a black screen.
Kazoeja
+1  A: 

Two small changes:

HBITMAP hBmp = CreateCompatibleBitmap(hNew, cropArea.right - cropArea.left, cropArea.bottom - cropArea.top); 

BitBlt(hNew, 0, 0, cropArea.right - cropArea.left, cropArea.bottom - cropArea.top, hSrc, cropArea.left, cropArea.top, SRCCOPY); 

You might want a little more checking to make sure the requested area falls within the size of the original bitmap.

Mark Ransom
Hmm, does not work. I think it has something to do with my creation of the HDC's.
Kazoeja
The DC creation looks OK to me. You should check the return values of everything, especially the `SelectObject`s.
Mark Ransom
+1  A: 

Never create a compatible bitmap from a 'fresh' memory DC. Unless that is you WANT to create a 1bpp bitmap - the default bitmap selected in a new memory DC is a 1x1 1bpp bitmap - so any compatible bitmap you create will match that. Which does tend to result in all black output.

Your color bitmap in in hSrc, so use that dc to make the new bitmap.

Chris Becke
A: 

Thanks for helping me. The function works perfectly now.

bool Bitmap::Crop(RECT cropArea)
{
HDC hSrc = CreateCompatibleDC(NULL);
SelectObject(hSrc, m_Handle);

HDC hNew = CreateCompatibleDC(hSrc);
HBITMAP hBmp = CreateCompatibleBitmap(hSrc, cropArea.right - cropArea.left, cropArea.bottom - cropArea.top); 
HBITMAP hOld = (HBITMAP)SelectObject(hNew, hBmp);

bool retVal = (BitBlt(hNew, 0, 0, cropArea.right - cropArea.left, cropArea.bottom - cropArea.top, hSrc, cropArea.left, cropArea.top, SRCCOPY))?true:false;

SelectObject(hNew, hOld);

DeleteDC(hSrc);
DeleteDC(hNew);

DeleteObject(m_Handle);

m_Handle = hBmp;

return retVal;
}
Kazoeja