Archive

Posts Tagged ‘COLORREF’

Retrieving current text color of a DC!

Use GetTextColor! Function signature is as follows…

// MFC
COLORREF GetTextColor() const;
// SDK
COLORREF GetTextColor( HDC hdc  ); // handle to DC
Advertisements

How to get color of a pixel from any Bitmap?

October 13, 2007 2 comments

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]

%d bloggers like this: