【发布时间】:2014-12-28 15:23:04
【问题描述】:
如何从 HBITMAP 中获取一个特定像素的 RGB 值?我尝试在 StackOverflow 上阅读类似的帖子,但没有一个真正适合这个问题。下面的代码似乎获得了 HBITMAP 中另一个位置(不是想要的位置)的 RGB 值。
int width = rc.right - rc.left;
int height = rc.bottom - rc.top;
HDC hdcSource = hdc; // the source device context
HBITMAP hSource = hbmp; // the bitmap selected into the device context
BITMAPINFO MyBMInfo = {0};
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
// Get the BITMAPINFO structure from the bitmap
if(0 == GetDIBits(hdcSource, hSource, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
{
// error handling
}
// create the pixel buffer
BYTE* Pixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];
// We'll change the received BITMAPINFOHEADER to request the data in a
// 32 bit RGB format (and not upside-down) so that we can iterate over
// the pixels easily.
// requesting a 32 bit image means that no stride/padding will be necessary,
// although it always contains an (possibly unused) alpha channel
MyBMInfo.bmiHeader.biBitCount = 32;
MyBMInfo.bmiHeader.biCompression = BI_RGB; // no compression -> easier to use
// correct the bottom-up ordering of lines (abs is in cstdblib and stdlib.h)
MyBMInfo.bmiHeader.biHeight = abs(MyBMInfo.bmiHeader.biHeight);
// Call GetDIBits a second time, this time to (format and) store the actual
// bitmap data (the "pixels") in the buffer lpPixels
if(0 == GetDIBits(hdcSource, hSource, 0, MyBMInfo.bmiHeader.biHeight,
Pixels, &MyBMInfo, DIB_RGB_COLORS))
{
// error handling
}
int PixelX = 221;
int PixelY = 14;
cout << "R: " << (int)Pixels[4*((PixelX-1)+(PixelY-1)*width)] << " | G: " << (int)Pixels[4*((PixelX-1)+(PixelY-1)*width)+1] << " | B: " << (int)Pixels[4*((PixelX-1)+(PixelY-1)*width)+2] << endl;
编辑(使用 user1118321 的解决方案)
height-1,因为 y 从 0 而不是 1 开始。
cout << "R: " << (int)Pixels[4*((PixelX)+(height-1-(PixelY))*width)] << " | G: " << (int)Pixels[4*((PixelX)+(height-1-(PixelY))*width)+1] << " | B: " << (int)Pixels[4*((PixelX)+(height-1-(PixelY))*width)+2] << endl;
【问题讨论】:
-
您在寻找
GetPixel吗? -
GetPixel 非常慢,这就是我使用 HBITMAP 将所有像素放入数组中的原因。
-
我很困惑。您想要的是“一个特定像素”还是“所有像素”?您的主要问题要求前者,现在在评论中您要求后者。是哪个?
-
We'll change the received BITMAPINFOHEADER to request the data in a 32 bit RGB format当你改变格式时,像素数据的大小当然也会改变。您根据原始格式分配的缓冲区可能对于新格式(尤其是 32bpp 格式)来说太小了。 -
您在
PixelX和PixelY上的数学似乎假设基于 1 的坐标。那是你要的吗?他们真的不是零基础吗?您可能不想从它们中减去一个。
标签: c++ bitmap rgb pixel hbitmap