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

How to access pixel color within a bitmap?

本文关键字:像素 颜色 位图 何访问 访问      更新时间:2023-10-16

我搜索了一下,知道我必须使用GetDIBits()。我不知道该如何处理LPVOID lpvBits out参数。

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

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

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

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来

我不确定这是否是您想要的,但GetPixel几乎满足了您的需求。。。至少我可以从函数的描述中看出