Crop function BitBlt(…)

﹥>﹥吖頭↗ 提交于 2019-12-20 03:18:32

问题


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.


回答1:


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.




回答2:


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;
}



回答3:


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.



来源:https://stackoverflow.com/questions/3671008/crop-function-bitblt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!