Search

Replace A Color in an Image with C#

Sometimes you need to replace one color in an image with another color. In C# we do this by first opening the image up from file and loading it into a Bitmap object. Once we have it in a Bitmap we can iterate over the x and y values looking at 1 pixel at a time. Each time we look at a pixel we can decide if we want to replace it with a new color based on it’s current color. After that we can save it to a new file, display it on screen, or both.

Replace Color Results

Here’s the input and output images so that you can see exactly what happened.

After running the above code on this image, here’s the output image that has red replaced with yellow.

Important Notes about LockBitmap

For the most part this is pretty simple code. The real “meat-and-potatoes” part is the function ReplaceColor. The first thing it does is lock the Bitmap object. In order to do this you need the LockBitmap class, which I explain on the How to Load an Image guide. If you need the LockBitmap class you can find it there.

Image Transperancy

After locking the Bitmap all we have to do is iterate over the width and height checking each pixel for a color match. Notice that the Color object includes an alpha, or transparency, channel. If you’re not sure what that means you might want to read our article about C# Color Objects.

C# Reference Types

You may have noticed that the main function ReplaceColor does not return a result. Instead it operates on the Bitmap object that was passed in. The Bitmap object is called a Reference Type in C#. This means that when you pass it to a function you are passing a reference to it as opposed to a copy. This makes it so that you do not have to create a second copy in RAM to modify and hand back to the calling function.

Categories

About Efundies

The goal of efundies.com is to provide the Internet with a collection of fun, free, electronics projects and advice.
Jason Bauer is an owner and programmer for Portforward.com. He's allergic to twitter and facebook, but you can find more of his articles in the Guides section.