Home > MFC > How to get color of a pixel from any Bitmap?

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…

#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]

Advertisements
  1. Amrit Agrawal
    January 28, 2011 at 12:11 pm

    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.

  2. November 10, 2007 at 5:34 am

    Thanks for the good information

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: