Search code examples
c++windowsgdi

How to draw RGB pixel data from memory with GDI in C++


I have a pointer to RGB data (640x480x3 bytes) that I want to draw into a window using BitBlt or something else equally fast. How do I convert the RGB data into something usable with BitBlt (for example).

Here is what I tried so far (without success)

    unsigned char *buf = theVI->getPixels(0);
    int size = theVI->getSize(0);
    int h = theVI->getHeight(0);
    int w = theVI->getWidth(0);

    HDC dc = GetDC(hwnd);
    HDC dcMem = CreateCompatibleDC(dc);

    HBITMAP bmp = CreateBitmap(w, h, 1, 24, buf);
    SelectObject(dcMem, bmp);
    BitBlt(dc, 0, 0, w, h, dcMem, 0, 0, SRCCOPY);

Thanks

UPDATE: this is the working code...

    HDC dc = GetDC(hwnd);

    BITMAPINFO info;
    ZeroMemory(&info, sizeof(BITMAPINFO));
    info.bmiHeader.biBitCount = 24;
    info.bmiHeader.biWidth = w;
    info.bmiHeader.biHeight = h;
    info.bmiHeader.biPlanes = 1;
    info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    info.bmiHeader.biSizeImage = size;
    info.bmiHeader.biCompression = BI_RGB;

    StretchDIBits(dc, 0, 0, w, h, 0, 0, w, h, buf, &info, DIB_RGB_COLORS, SRCCOPY);
    ReleaseDC(hwnd, dc);

Solution

  • You can render your bytes ( that are so called DIB device independent bitmap ) to HDC using StretchDIBits API function.

    And yet check DIB article in MSDN