How to get color of a pixel from any Bitmap?

It’s easy to get color of a pixel from a bitmap. Here is a function which does this…

[sourcecode language=’cpp’]#include
#include

// Returns Pixel color from bitmap
COLORREF GetPixelValueFromBitmap( const int x, const int y, CBitmap& bmp )
{
// DC for desktop
CDC dcDesktop;
dcDesktop.Attach( ::GetDC( GetDesktopWindow() ));

// Create a DC compatible with desktop or any other existing window
CDC dc;
dc.CreateCompatibleDC( &dcDesktop );

// Save the DC settings here, so that we can restore it later
const int nRestorePoint = dc.SaveDC();

// Select the bitmap into the DC
dc.SelectObject( &bmp );

// Now get the pixels value from the DC
const COLORREF clr = dc.GetPixel( x, y );

// Restore DC settings
dc.RestoreDC( nRestorePoint );

// Return pixel value/color
return clr;
}// End GetPixelValueFromBitmap

// main function
int main()
{
// initialize MFC and print an error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
std::cerr << _T("Fatal Error: MFC initialization failed") << std::endl; return 1; } // Prepare a bitmap CBitmap bmp; // Provide your own bitmap id bmp.LoadBitmap( IDB_BITMAP1 ); // Get color of given pixel from given bitmap COLORREF clr = GetPixelValueFromBitmap( 0, 2, bmp ); // Split up the colors and see const int Red = GetRValue( clr ); const int Green = GetGValue( clr ); const int Blue = GetBValue( clr ); return 0; }// End main[/sourcecode]

2 thoughts on “How to get color of a pixel from any Bitmap?

  1. I want the color of every pixel of a bitmap image. because I want it’s alpha value. I tried GetPixel() but it very slow and GetDIBits() is not giving proper color as I compare the same with GetPixel() method.

    Pls Suggest me some proper solution to do that.

Appreciate your comments...