Vercas Vercas - 2 months ago 9
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:

Color.FromArgb(
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

The formula for calculating the new pixel is:

newColor.R=OldColor;
newColor.G=OldColor;
newColor.B=255;

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

newColor.R=OldColor+(1-oldColor/255.0)*TargetColor.R;
newColor.G=OldColor+(1-oldColor/255.0)*TargetColor.G;
newColor.B=OldColor+(1-oldColor/255.0)*TargetColor.B;

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.