Search code examples
c#graphicscolorspngwmf

C# Remove color using Graphics


I'm looking to remove all color from WMF image file by only 1 color.

Metafile img = new Metafile(path + strFilename + ".wmf");
float planScale = 0.06615f;
float scale = 1200f / (float)img.Width;
planScale = planScale / scale; ;
float widht = img.Width * scale;
float height = img.Height * scale;
using (var target = new Bitmap((int)widht, (int)height))
{
    using (var g = Graphics.FromImage(target))
    {
        g.DrawImage(img, 0, 0, (int)widht, (int)height);
        target.Save("image.png", ImageFormat.Png);
    }
}

For the moment, I load a WMF file, set the scale and save it as PNG file.

Example of PNG result: enter image description here

But now I need to remove all the colors (green, purple....) and set only 1 color like Gray for example.


Solution

  • If the background is always white you can do something like that. You can change the 200 to something you want, to adjust the Color that shouldn't be changed. In this example the white color is not changed. If you don't want to draw black, you can adjust the Color at target.SetPixel(x,y,Color.Black);

    Metafile img = new Metafile("D:\\Chrysanthemum.wmf");
    float planScale = 0.06615f;
    float scale = 1200f / (float)img.Width;
    planScale = planScale / scale; ;
    float widht = img.Width * scale;
    float height = img.Height * scale;
    using (var target = new Bitmap((int)widht, (int)height))
    {
        using (var g = Graphics.FromImage(target))
        {
            g.DrawImage(img, 0, 0, (int)widht, (int)height);
        }
    
        for (int x = 0; x < target.Width; x++)
        {
            for (int y = 0; y < target.Height; y++)
            {
                Color white = target.GetPixel(x, y);
                if ((int)white.R > 200 || (int)white.G > 200 || (int)white.B > 200)
                {
                    target.SetPixel(x, y, Color.Black);
                }
            }
        }
    
    target.Save("D:\\image.png", ImageFormat.Png);
    }
    

    WMF Image: enter image description here

    PNG Image: enter image description here

    I hope that is what you are searching for.