getting a RGB value from a pixel and setting the rgb values back to the same pixel
-
25-09-2019 - |
Question
In the code snippet below I am trying to retrieve the RGB values of a pixel in Visual C++ and then set the same RGB values back to be the same pixel. i.e. this is just a test. However when I do it the resulting image is similar but the colors are wrong/off. The resulting image appears to be totally missing the yellow color pixels of the original image. Why am I not getting the same image back after this? Any help would be most appreciated. Thanks
BYTE *pbBitmap;
HBITMAP hDestBitmap = CreateDIBSection(memDC1, &bi, DIB_RGB_COLORS,(void**)&pbBitmap, NULL, 0);
if (hDestBitmap){
SelectObject(DestDC2, hDestBitmap);
BitBlt(DestDC2, 0, 0, nX, nY, memDC1, 0, 0, SRCCOPY);
RGBQUAD *pRGB;
LONG nPixels;
for (pRGB = (RGBQUAD *)pbBitmap, nPixels = (nX * nY); nPixels > 0; ++pRGB, --nPixels){
ULONG* pSrc =(ULONG*)pRGB;
ULONG nRed = GetRValue(*pSrc);
ULONG nGreen = GetGValue(*pSrc);
ULONG nBlue = GetBValue(*pSrc);
pRGB->rgbRed=nRed;
pRGB->rgbGreen=nGreen;
pRGB->rgbBlue=nBlue;
}
CRect rctPicture2;
m_Picture2.GetWindowRect(&rctPicture2);
ScreenToClient(&rctPicture2);
dc.SetStretchBltMode(COLORONCOLOR);
StretchBlt(dc,rctPicture2.left,rctPicture2.top,rctPicture2.Width(),rctPicture2.Height(),DestDC2,0,0,1152,864,SRCCOPY);
}
Solution
The way you are accessing the colour values is wrong. GetRValue
and other functions are meant to operate on a COLORREF
value which is laid out in memory as red-green-blue-reserved
, whereas the format of an RGBQUAD
is blue-green-red-reserved
. By using the Get?Value
macros on an RGBQUAD
, you're swapping the red and blue channels.