现在的位置: 首页 > 综合 > 正文

GetDIBits()和GetBitmapBits()用法简介

2014年01月26日 ⁄ 综合 ⁄ 共 2113字 ⁄ 字号 评论关闭

原型声明:
int GetDIBits(HDC hdc, HBITMAP hbmp, UINT uStartScan, UINT uScanLines, LPVOID lpvBits, LPBITMAPINFO lpbi, UINT uUsage);
DWORD CBitmap::GetBitmapBits(DWORD dwCount, LPVOID lpBits) const;

//使用GetDIBits()
CDC* dcMem; //赋值省略
CBitmap* pBM = dcMem->GetCurrentBitmap(); //从CDC中获取资源,或直接用CBitmap载入资源
BITMAP bmptemp = {0};
HBITMAP hbmp = (HBITMAP)pBM->GetSafeHandle();

if (!::GetObject(hbmp, sizeof(BITMAP), (LPBYTE)&bmptemp))  
return false;  

BYTE imgSize = bmptemp.bmBitsPixel / 8; //兼容24bit和32bit位图

// 定义位图信息  
BITMAPINFO bi;  
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);  
bi.bmiHeader.biWidth = bmptemp.bmWidth;  
bi.bmiHeader.biHeight = bmptemp.bmHeight;  
bi.bmiHeader.biPlanes = 1;  
bi.bmiHeader.biBitCount = bmptemp.bmBitsPixel;   
bi.bmiHeader.biCompression = BI_RGB;   
bi.bmiHeader.biSizeImage = bmptemp.bmWidth * imgSize * bmptemp.bmHeight;
bi.bmiHeader.biClrUsed = 0;  
bi.bmiHeader.biClrImportant = 0;  
  
// 获取位图数据  
CClientDC hdc(this);
BYTE* lpvBits = new BYTE[bi.bmiHeader.biSizeImage];  
::ZeroMemory(lpvBits, bi.bmiHeader.biSizeImage);  
if (!::GetDIBits(hdc, hbmp, 0, bmptemp.bmHeight, lpvBits, &bi, DIB_RGB_COLORS))  
{  
delete [] lpvBits;  
lpvBits = NULL;  
}

int temp = 0;

BYTE buffer = 0;
for(int j = bmptemp.bmHeight - 1;j >= 0;j--)
{
for(int i = bmptemp.bmWidth - 1;i >= 0;i--)
{
   buffer = lpvBits[(j * bmptemp.bmWidth + i) * imgSize];
   memcpy(&pData[temp++], &buffer, 1);
}
}

if(lpvBits != 0)
{
delete [] lpvBits;
lpvBits = 0;
}
*******************************************************************************************
//使用GetBitmapBits()
CDC* dcMem;
CBitmap* pBM = dcMem->GetCurrentBitmap();
BITMAP bmptemp = {0};
pBM->GetBitmap(&bmptemp);

BYTE imgSize = bmptemp.bmBitsPixel / 8;  
BYTE* lpvBits = new BYTE[bmptemp.bmWidth * bmptemp.bmHeight * imgSize];
::ZeroMemory(lpvBits, bmptemp.bmWidth * bmptemp.bmHeight * imgSize);
long sizeofdata = pBM->GetBitmapBits(bmptemp.bmWidth * bmptemp.bmHeight * imgSize, lpvBits);
if(0 == sizeofdata)
{
delete [] lpvBits;  
lpvBits = NULL;
}

int temp = 0;

BYTE buffer = 0;
for(int j = bmptemp.bmHeight - 1;j >= 0;j--)
{
for(int i = 0;i < bmptemp.bmWidth;i++)
{
   buffer = lpvBits[(j * bmptemp.bmWidth + i) * imgSize];
   memcpy(&pData[temp++], &buffer, 1);
}
}

if(lpvBits != 0)
{
delete [] lpvBits;
lpvBits = 0;
}

使用GetCurrentBitmap()在极少数情况下,得到的位图会有序的乱码。当出现此种情况,可创建临时CDC对象,完成CBitmap间的复制,具体请参见上一篇《MFC中CDC之间的复制方法》。

 

抱歉!评论已关闭.