首页 > 解决方案 > C# 使用图形去除颜色

问题描述

我希望WMF仅通过一种颜色从图像文件中删除所有颜色。

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);
    }
}

目前,我加载一个WMF文件,设置比例并将其保存为PNG文件。

PNG结果示例: 在此处输入图像描述

但现在我需要删除所有颜色(绿色、紫色......)并只设置一种颜色,例如灰色。

标签: c#graphicscolorspngwmf

解决方案


如果背景总是白色的,你可以做这样的事情。您可以将 更改200为您想要的内容,以调整不应更改的颜色。在这个例子中,白色没有改变。如果你不想画黑色,你可以调整颜色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 图像: 在此处输入图像描述

PNG图像: 在此处输入图像描述

我希望这就是你正在寻找的。


推荐阅读