如何访问位图中的像素颜色?

时间:2012-01-25 12:07:16

标签: c++ c windows graphics

我搜索过,我明白我必须使用GetDIBits()。我不知道如何处理LPVOID lpvBits out参数。

有人可以向我解释一下吗?我需要以二维矩阵形式获取像素颜色信息,以便我可以检索特定(x,y)坐标对的信息。

我使用Win32 API在C ++中编程。

2 个答案:

答案 0 :(得分:5)

首先你需要一个位图并打开它

HBITMAP hBmp = (HBITMAP) LoadImage(GetModuleHandle(NULL), _T("test.bmp"), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);

if(!hBmp) // failed to load bitmap
    return false;

//getting the size of the picture
BITMAP bm;
GetObject(hBmp, sizeof(bm), &bm);
int width(bm.bmWidth),
    height(bm.bmHeight);

//creating a bitmapheader for getting the dibits
BITMAPINFOHEADER bminfoheader;
::ZeroMemory(&bminfoheader, sizeof(BITMAPINFOHEADER));
bminfoheader.biSize        = sizeof(BITMAPINFOHEADER);
bminfoheader.biWidth       = width;
bminfoheader.biHeight      = -height;
bminfoheader.biPlanes      = 1;
bminfoheader.biBitCount    = 32;
bminfoheader.biCompression = BI_RGB;

bminfoheader.biSizeImage = width * 4 * height;
bminfoheader.biClrUsed = 0;
bminfoheader.biClrImportant = 0;

//create a buffer and let the GetDIBits fill in the buffer
unsigned char* pPixels = new unsigned char[(width * 4 * height)];
if( !GetDIBits(CreateCompatibleDC(0), hBmp, 0, height, pPixels, (BITMAPINFO*) &bminfoheader, DIB_RGB_COLORS)) // load pixel info 
{ 
    //return if fails but first delete the resources
    DeleteObject(hBmp);
    delete [] pPixels; // delete the array of objects

    return false;
}

int x, y; // fill the x and y coordinate

unsigned char r = pPixels[(width*y+x) * 4 + 2];
unsigned char g = pPixels[(width*y+x) * 4 + 1];
unsigned char b = pPixels[(width*y+x) * 4 + 0]; 

//clean up the bitmap and buffer unless you still need it
DeleteObject(hBmp);
delete [] pPixels; // delete the array of objects

所以简而言之,lpvBits out参数是指向像素的指针 但如果它只有1个像素你需要我建议使用getpixel

答案 1 :(得分:1)

我不确定这是否是您正在寻找的内容,但GetPixel几乎可以满足您的需求...至少从我可以从函数说明中看出来