【转】如何从HDC中获取位图信息

来源:互联网 发布:淘宝好评怎么写 编辑:程序博客网 时间:2024/05/16 18:22
// 从DC中获取位图
int GetBmpFromDc()
{
    HDC          hMemDC;
    HBITMAP      hBmp;
    BITMAP       bmp;
    HANDLE       hOld;
    HDC          hDC;
    RECT         rcWnd;

    // 获取子窗口的绘图区域
    ::GetWindowRect(m_hWnd, &rcWnd);

    // 计算子窗口绘图区域的宽度和高度
    int nWidth = rcWnd.right - rcWnd.left;
    int nHeight = rcWnd.bottom - rcWnd.top;

    // 获取子窗口 DC
    hDC = ::GetDC(m_hWnd);
    if (! hDC)
    {
        m_bBmpIsValid = false;
        return FALSE;
    }

    // 将窗口内容复制到内存 DC 中
    hMemDC = CreateCompatibleDC(hDC);
    hBmp    = CreateCompatibleBitmap(hDC, nWidth, nHeight);
    hOld    = SelectObject(hMemDC, hBmp);
    BOOL rt = BitBlt(hMemDC, 0, 0, nWidth, nHeight, hDC, 0, 0, SRCCOPY);
    if (! rt)
    {
        m_bBmpIsValid = false;
        
        // 释放资源
        ::DeleteObject(hBmp);
        ::DeleteDC(hMemDC);
        ::ReleaseDC(m_hWnd, hDC);

        return FALSE;
    }

    // 从内存 DC 中获取 BITMAP
    hBmp = (HBITMAP) SelectObject(hMemDC, hOld);

    // 获取位图基本信息
    ::GetObject(hBmp, sizeof(bmp), &bmp);

    // 获取位图头信息
    BITMAPINFO bmpInfo;
    bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmpInfo.bmiHeader.biBitCount = 0;
    if (! GetDIBits(hMemDC, hBmp, 0, 1, NULL, &bmpInfo, DIB_RGB_COLORS))
    {
        // 释放资源
        ::DeleteObject(hBmp);
        ::DeleteDC(hMemDC);
        ::ReleaseDC(m_hWnd, hDC);

        return FALSE;
    }

    // 设置位图的压缩格式为 BI_RGB,16位时像素格式为RGB555
    bmpInfo.bmiHeader.biCompression = BI_RGB;

    // 分配内存,用于存储位图数据
    bmp.bmBits = (LPVOID) GlobalAlloc(GMEM_FIXED,
                                      bmpInfo.bmiHeader.biSizeImage);

    // 获取位图数据
    if (NULL != bmp.bmBits && ! GetDIBits(hMemDC, hBmp, 0,
        (WORD) bmp.bmHeight, (LPVOID) bmp.bmBits, &bmpInfo, DIB_RGB_COLORS))
    {
        // 释放资源
        ::DeleteObject(hBmp);
        ::DeleteDC(hMemDC);
        ::GlobalFree((HGLOBAL) bmp.bmBits);
        ::ReleaseDC(m_hWnd, hDC);

        return FALSE;
    }

    // 释放资源
    ::DeleteObject(hBmp);
    ::DeleteDC(hMemDC);
    ::ReleaseDC(m_hWnd, hDC);

    m_bBmpIsValid = true;
    return TRUE;
}
原创粉丝点击