Search code examples
c++bitmaprgbpixelhbitmap

How to get RGBQUAD from HBITMAP?


I'm currently studying windows programming and writing a small image searching program.

I want to get (R, G, B) data of (x, y)pixel when I have HBITMAP handle of the image.

So, I tried to write something like this

//already have HBITMAP.

struct RGBpixel
{
int x, y;
unsigned char R, G, B;
};

bool getRGB(HBITMAP h_image, RGBpixel* pixel, x, y)
{
...
// put x, y values to pixel.x, pixel.y 
// put R, G, B values to pixel.R, pixel.G, pixel.B
...
return true;
}

How can I write this?

I'd seen about GetPixel function but it was too slow for my program :( Any other fater method?


Solution

  • With a bitmap handle HBITMAP you don't necessarily have access to bitmap data. Then in turn the bitmap pixel formats vary.

    To get access to the data and be able to address pixels directly without having to use per-pixel API calls, you need to create a DIB (with CreateDIBSection API or alike) and copy original bitmap there or have the original bitmap created respectively in first place.

    The CreateDIBSection function creates a DIB that applications can write to directly. The function gives you a pointer to the location of the bitmap bit values.

    Similary, GetDIBits will get a copy of bitmap data. The advantage of CreateDIBSection is that you can have bitmap and pointer to actual data in the same time without doing conversions both ways as you use the bitmap.