string sourceFolder = @"S:\Study_Dot_net\images_remove_colour\ConsoleApp1\ConsoleApp1\bin\Debug";
string originalImageName= @"image_01.jpg";
string finalImage = @"image_final_01.jpg";
Bitmap img = new Bitmap(Path.Combine(sourceFolder, originalImageName));
float widht = img.Width;
float height = img.Height;
using (var target = new Bitmap((int)widht, (int)height))
{
using (var g = Graphics.FromImage(target))
{
g.DrawImage(img, 0, 0, (int)widht, (int)height);
}
Color baseColour = Color.White;
Color colourToReplaceWith = Color.White;
int tolerance = 20;
for (int x = 0; x < target.Width; x++)
{
for (int y = 0; y < target.Height; y++)
{
// get background colour
if(x==0 && y==0)
{
baseColour = target.GetPixel(x, y);
}
Color currentColour = target.GetPixel(x, y);
if (
((int)currentColour.R >= (int)baseColour.R- tolerance && (int)currentColour.R <= (int)baseColour.R + tolerance)
&& ((int)currentColour.G >= (int)baseColour.G - tolerance && (int)currentColour.G <= (int)baseColour.G + tolerance)
&& ((int)currentColour.B >= (int)baseColour.B - tolerance && (int)currentColour.B <= (int)baseColour.B + tolerance)
)
{
target.SetPixel(x, y, colourToReplaceWith);
}
}
}
string resultImage = Path.Combine(sourceFolder, finalImage);
if(File.Exists(resultImage))
{
File.Delete(resultImage);
}
target.Save(resultImage, ImageFormat.Jpeg);
}