【问题标题】:How to access pixel color within a bitmap?如何访问位图中的像素颜色?
【发布时间】:2012-01-25 12:07:15
【问题描述】:

我搜索并知道我必须使用@987654321@LPVOID lpvBits out 参数不知道怎么处理。

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

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

【问题讨论】:

标签: c++ c windows graphics


【解决方案1】:

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

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 来

【讨论】:

    【解决方案2】:

    我不确定这是否是您正在寻找的东西,但 GetPixel 几乎可以满足您的需求......至少我可以从函数的描述中看出

    【讨论】:

    • 您通常不想使用 GetPixel 来提取所有像素,它会变得很慢。
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2011-08-20
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2019-03-25
    相关资源
    最近更新 更多