c++ Get raw pixel data from hbitmap

前端 未结 3 1584
余生分开走
余生分开走 2021-01-02 20:09

I am fairly new to using p/invoke calls and am wondering if someone can guide me on how to retrieve the raw pixel data (unsigned char*) from an hbitmap.

This is my

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 20:33

    First, an HBITMAP shouldn't be a unsigned char*. If you are passing an HBITMAP to C++ then the parameter should be an HBITMAP:

    int Resize::ResizeImage(HBITMAP hBmp)

    Next to convert from HBITMAP to pixels:

    std::vector ToPixels(HBITMAP BitmapHandle, int &width, int &height)
    {        
        BITMAP Bmp = {0};
        BITMAPINFO Info = {0};
        std::vector Pixels = std::vector();
    
        HDC DC = CreateCompatibleDC(NULL);
        std::memset(&Info, 0, sizeof(BITMAPINFO)); //not necessary really..
        HBITMAP OldBitmap = (HBITMAP)SelectObject(DC, BitmapHandle);
        GetObject(BitmapHandle, sizeof(Bmp), &Bmp);
    
        Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
        Info.bmiHeader.biWidth = width = Bmp.bmWidth;
        Info.bmiHeader.biHeight = height = Bmp.bmHeight;
        Info.bmiHeader.biPlanes = 1;
        Info.bmiHeader.biBitCount = Bmp.bmBitsPixel;
        Info.bmiHeader.biCompression = BI_RGB;
        Info.bmiHeader.biSizeImage = ((width * Bmp.bmBitsPixel + 31) / 32) * 4 * height;
    
        Pixels.resize(Info.bmiHeader.biSizeImage);
        GetDIBits(DC, BitmapHandle, 0, height, &Pixels[0], &Info, DIB_RGB_COLORS);
        SelectObject(DC, OldBitmap);
    
        height = std::abs(height);
        DeleteDC(DC);
        return Pixels;
    }
    

提交回复
热议问题