Color Substitution
This algorithm replaces the specified source color with the new color.
public static void ApplyColorSubstitution(ref Bitmap bmp, int threshold, System.Drawing.Color sourceColor, System.Drawing.Color newColor)
{
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* ptr = (byte*)bmpData.Scan0.ToPointer();
int stopAddress = (int)ptr + bmpData.Stride * bmpData.Height;
int SrcTotalRGB = sourceColor.R + sourceColor.G + sourceColor.B;
int TotalRGB;
while ((int)ptr != stopAddress)
{
TotalRGB = ptr[0] + ptr[1] + ptr[2];
if (Math.Abs(SrcTotalRGB - TotalRGB) < threshold)
{
ptr[0] = newColor.B;
ptr[1] = newColor.G;
ptr[2] = newColor.R;
}
ptr += 3;
}
}
bmp.UnlockBits(bmpData);
}
Example
Bitmap b = (Bitmap)Image.FromFile("rose.jpg");
ApplyColorSubstitution(ref b, 50, Color.Green, Color.Blue);