Click here to Skip to main content
11,923,046 members (62,958 online)
Click here to Skip to main content
Add your own
alternative version


80 bookmarked

How to replace a color in an HBITMAP

, 5 Feb 2012 Public Domain
Rate this:
Please Sign up or sign in to vote.
Replacing a color by another in transparent bitmaps.

Replace color screenshot


When I wrote this function my problem was to replace one color by another on transparent bitmaps. My images were resources bitmaps, which I store in an ImageList for easy transparency.

There is no easy way to directly access a bitmap's pixel on Win32. If you're interested in doing that, this article may help you understand the usage of CreateDIBSection.

  • If you have to load a bitmap from a resource and make many color replacements, or if you have to change a color in a HBITMAP, this function is for you.
  • If you have a bitmap in a resource and want to replace one or more colors on load, it's better to use CreateMappedBitmap. You can find in the sample program a ReplaceColor function which uses CreateMappedBitmap.

I've made the same code using only BitBlt. BitBlt is really fast but the creation of the mask bitmap is so slow that the whole function is twice slower than the code using CreateDIBSection (sources are in the sample).


My code always return a 32 bit bitmap. If you need to keep your original bitmap bit per pixels, you'll have two options:

  • You can rewrite it with GetDIBits. You will need special code for monochromes to 32 bit bitmaps.
  • You can BitBlt the 32 bit bitmap to your less color DC. It's easy, slow, and you will lose some colors in the process.

Sample program

The sample program you can download does the following:

  • Creates a window in WinMain.
  • Loads a bitmap from resources WM_NCCREATE.
  • Adds this bitmap to an ImageList WM_NCCREATE.
  • Uses ReplaceColor to get a copy of the bitmap with one color replaced by another (4 times) WM_NCCREATE.
  • Displays all the stored images in the window WM_PAINT.
  • Cleans everything WM_DESTROY.

Easy to use

A short sample of the usage of ReplaceColor:

HBITMAP hBmp = ReplaceColor(hBmp2,0xff0000,0x00ff00); // replace blue by green

// Use your modified Bitmap here 


ReplaceColor source code

The ReplaceColor function is a pure Win32 function. It doesn't make any use of MFC. Its code is standalone, you can cut and paste it without modifications to your code.

#define COLORREF2RGB(Color) (Color & 0xff00) | ((Color >> 16) & 0xff) \
                                 | ((Color << 16) & 0xff0000)

// ReplaceColor
// Author    : Dimitri Rochette
// Specials Thanks to Joe Woodbury for his comments and code corrections
// Includes  : Only <windows.h>

// hBmp         : Source Bitmap
// cOldColor : Color to replace in hBmp
// cNewColor : Color used for replacement
// hBmpDC    : DC of hBmp ( default NULL ) could be NULL if hBmp is not selected
// Retcode   : HBITMAP of the modified bitmap or NULL for errors
    if (hBmp)
        HDC BufferDC=CreateCompatibleDC(NULL);    // DC for Source Bitmap
        if (BufferDC)
            HBITMAP hTmpBitmap = (HBITMAP) NULL;
            if (hBmpDC)
                if (hBmp == (HBITMAP)GetCurrentObject(hBmpDC, OBJ_BITMAP))
                hTmpBitmap = CreateBitmap(1, 1, 1, 1, NULL);
                SelectObject(hBmpDC, hTmpBitmap);

            HGDIOBJ PreviousBufferObject=SelectObject(BufferDC,hBmp);
            // here BufferDC contains the bitmap
            HDC DirectDC=CreateCompatibleDC(NULL); // DC for working
            if (DirectDC)
                // Get bitmap size
                BITMAP bm;
                GetObject(hBmp, sizeof(bm), &bm);

                // create a BITMAPINFO with minimal initilisation 
                // for the CreateDIBSection
                BITMAPINFO RGB32BitsBITMAPINFO; 

                // pointer used for direct Bitmap pixels access
                UINT * ptPixels;    

                HBITMAP DirectBitmap = CreateDIBSection(DirectDC, 
                                       (BITMAPINFO *)&RGB32BitsBITMAPINFO, 
                                       (void **)&ptPixels, 
                                       NULL, 0);
                if (DirectBitmap)
                    // here DirectBitmap!=NULL so ptPixels!=NULL no need to test
                    HGDIOBJ PreviousObject=SelectObject(DirectDC, DirectBitmap);

                       // here the DirectDC contains the bitmap

                    // Convert COLORREF to RGB (Invert RED and BLUE)

                    // After all the inits we can do the job : Replace Color
                    for (int i=((bm.bmWidth*bm.bmHeight)-1);i>=0;i--)
                        if (ptPixels[i]==cOldColor) ptPixels[i]=cNewColor;
                    // little clean up
                    // Don't delete the result of SelectObject because it's 
                    // our modified bitmap (DirectBitmap)

                    // finish
                // clean up
            if (hTmpBitmap)
                SelectObject(hBmpDC, hBmp);
            // BufferDC is now useless
    return RetBmp;


This article, along with any associated source code and files, is licensed under A Public Domain dedication


About the Author

Dimitri Rochette
Software Developer (Senior)
France France
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionMemory Leak can happen if.... Pin
Member 1152513214-Mar-15 9:09
memberMember 1152513214-Mar-15 9:09 
AnswerRe: Memory Leak can happen if.... Pin
Dimitri Rochette14-Mar-15 10:08
memberDimitri Rochette14-Mar-15 10:08 
GeneralMy vote of 5 Pin
24532452433-Oct-12 15:35
member24532452433-Oct-12 15:35 
GeneralMy vote of 3 Pin
Mukit, Ataul5-Feb-12 20:31
memberMukit, Ataul5-Feb-12 20:31 
GeneralRe: My vote of 3 Pin
sgllama5-Feb-12 23:14
membersgllama5-Feb-12 23:14 
GeneralRe: My vote of 3 Pin
sgllama5-Feb-12 23:26
membersgllama5-Feb-12 23:26 
GeneralRe: My vote of 3 Pin
Mukit, Ataul5-Feb-12 23:29
memberMukit, Ataul5-Feb-12 23:29 
GeneralMy vote of 5 Pin
Abinash Bishoyi5-Feb-12 7:11
memberAbinash Bishoyi5-Feb-12 7:11 
Questiongreate code Pin
szk.sh7-Dec-11 17:17
memberszk.sh7-Dec-11 17:17 
QuestionRewrite available for .Net either VB.Net or C#? Pin
Tim8w2-Jul-08 6:50
memberTim8w2-Jul-08 6:50 
GeneralBrilliant Pin
Ali Imran Khan Shirani29-Jun-08 6:25
memberAli Imran Khan Shirani29-Jun-08 6:25 
Generalcan't build Pin
k_meleon20-Mar-08 23:44
memberk_meleon20-Mar-08 23:44 
GeneralArtist needs help Pin
pxfragonard29-Jan-07 14:32
memberpxfragonard29-Jan-07 14:32 
GeneralProblem on WinCE 3.0 Pin
Allen228-Sep-06 6:29
memberAllen228-Sep-06 6:29 
      My colleague used the same code for out client application. It works fine on all versions of wince, except WinCE 3.0.
      The problem is that CreateDIBSection returns NULL. I used getLastError and found that the error is
      I checked wince help and found this function is supported winCE 1.0 and later.

      Anybody has any suggestion?


GeneralRe: Problem on WinCE 3.0 Pin
Dimitri Rochette28-Sep-06 9:58
memberDimitri Rochette28-Sep-06 9:58 
GeneralA little shorter variant of "BlitReplaceColor" Pin
Yuri Machlin23-Jun-06 2:07
memberYuri Machlin23-Jun-06 2:07 
GeneralRe: A little shorter variant of "BlitReplaceColor" Pin
Dimitri Rochette24-Jun-06 10:30
memberDimitri Rochette24-Jun-06 10:30 
Generalconverting values Pin
dSolariuM27-Apr-06 12:29
memberdSolariuM27-Apr-06 12:29 
GeneralRe: converting values Pin
Dimitri Rochette28-Apr-06 0:22
memberDimitri Rochette28-Apr-06 0:22 
GeneralRe: converting values Pin
dSolariuM28-Apr-06 4:15
memberdSolariuM28-Apr-06 4:15 
GeneralBitmap bit access Pin
Georgi Petrov28-Dec-04 3:56
memberGeorgi Petrov28-Dec-04 3:56 
GeneralRe: Bitmap bit access Pin
Dimitri Rochette28-Dec-04 10:43
memberDimitri Rochette28-Dec-04 10:43 
GeneralRe: Bitmap bit access Pin
Georgi Petrov28-Dec-04 21:16
memberGeorgi Petrov28-Dec-04 21:16 
QuestionWhy not sent changed bmmp to clipboard? Pin
sunwolf_00118-Oct-04 17:16
membersunwolf_00118-Oct-04 17:16 
GeneralLoading bitmap Pin
vivadotnet23-Jun-04 9:23
membervivadotnet23-Jun-04 9:23 
GeneralRe: Loading bitmap Pin
Dimitri Rochette23-Jun-04 11:30
memberDimitri Rochette23-Jun-04 11:30 
GeneralThanks for the code snipit Pin
SAHorowitz19-Apr-04 5:03
memberSAHorowitz19-Apr-04 5:03 
QuestionHow can i change a specific Pixel in a Bitmap to Transparent Pin
Azhar Javaid21-Jul-03 2:21
memberAzhar Javaid21-Jul-03 2:21 
AnswerRe: How can i change a specific Pixel in a Bitmap to Transparent Pin
Dimitri Rochette21-Jul-03 14:02
memberDimitri Rochette21-Jul-03 14:02 
QuestionGetting hbitmap from imagelist ? Pin
selecta16-Jan-03 13:33
memberselecta16-Jan-03 13:33 
AnswerRe: Getting hbitmap from imagelist ? Pin
Dimitri Rochette16-Jan-03 14:11
memberDimitri Rochette16-Jan-03 14:11 
GeneralRe: Getting hbitmap from imagelist ? Pin
selecta16-Jan-03 15:15
memberselecta16-Jan-03 15:15 
GeneralPossible Alternative Pin
Anonymous27-Sep-02 5:47
sussAnonymous27-Sep-02 5:47 
GeneralRe: Possible Alternative Pin
WREY28-Sep-02 12:48
memberWREY28-Sep-02 12:48 
GeneralPossible problems with the code Pin
Joe Woodbury17-Sep-02 21:48
memberJoe Woodbury17-Sep-02 21:48 
GeneralRe: Possible problems with the code Pin
Dimitri Rochette20-Sep-02 15:48
memberDimitri Rochette20-Sep-02 15:48 
GeneralRe: Possible problems with the code Pin
Joe Woodbury20-Sep-02 17:51
memberJoe Woodbury20-Sep-02 17:51 
GeneralRe: Possible problems with the code Pin
Dimitri Rochette21-Sep-02 8:22
memberDimitri Rochette21-Sep-02 8:22 
GeneralRe: Possible problems with the code Pin
Harald Krause27-Sep-02 2:13
memberHarald Krause27-Sep-02 2:13 
GeneralRe: Possible problems with the code Pin
Anonymous17-Feb-03 17:34
sussAnonymous17-Feb-03 17:34 
General. Pin
Goran Mitrovic4-Sep-02 14:19
memberGoran Mitrovic4-Sep-02 14:19 
GeneralRe: . Pin
Dimitri Rochette6-Sep-02 11:52
memberDimitri Rochette6-Sep-02 11:52 
GeneralRe: . Pin
Goran Mitrovic6-Sep-02 15:27
memberGoran Mitrovic6-Sep-02 15:27 
Generala stupid question... Pin
Paolo Messina4-Sep-02 12:55
memberPaolo Messina4-Sep-02 12:55 
GeneralRe: a stupid question... Pin
Christian Graus4-Sep-02 13:03
memberChristian Graus4-Sep-02 13:03 
GeneralRe: a stupid question... Pin
Paolo Messina4-Sep-02 14:25
memberPaolo Messina4-Sep-02 14:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151125.3 | Last Updated 5 Feb 2012
Article Copyright 2002 by Dimitri Rochette
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid