Vercas Vercas - 1 year ago 137
C# Question

How do I recolor an image? (see images)

How do I achieve this kind of color replacement programmatically?
replacing black with blue

So this is the function I have used to replace a pixel:

oldColorInThisPixel.R + (byte)((1 - oldColorInThisPixel.R / 255.0) * colorToReplaceWith.R),
oldColorInThisPixel.G + (byte)((1 - oldColorInThisPixel.G / 255.0) * colorToReplaceWith.G),
oldColorInThisPixel.B + (byte)((1 - oldColorInThisPixel.B / 255.0) * colorToReplaceWith.B)

Thank you, CodeInChaos!

Answer Source

The formula for calculating the new pixel is:


Generalizing to arbitrary colors:

I assume you want to map white to white and black to that color. So the formula is newColor=TargetColor+(White-TargetColor)*Input


And then just iterate over the pixels of the image(byte array) and write them to a new RGB array. There are many threads on how to copy an image into a byte array and manipulate it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download