【问题标题】:C# Remove color using GraphicsC# 使用图形去除颜色
【发布时间】:2019-02-15 01:32:35
【问题描述】:

我希望从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 结果示例:

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

【问题讨论】:

  • 试试这个 - 因为你提到了灰色 - stackoverflow.com/questions/2265910/…
  • 你想要一张只有白色或一个特定灰度值的二值图像,还是应该将不同的颜色映射到不同的灰度值?
  • 如果你想要一个灰度,认为在RGB中,灰色调是那些R = G = B的颜色。如果你想要一个二值图像(黑色和白色),你需要选择一个阈值并将通道设置为 0 或 255(低于或高于阈值)。

标签: c# graphics colors png wmf


【解决方案1】:

如果背景总是白色的,你可以这样做。您可以将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 图片:

我希望这就是您要搜索的内容。

【讨论】:

  • 这太慢了。使用 ColorMatrix 的速度非常快。使用LockBits 可以让您既快速又全面地控制。
  • 是的,你是对的,它非常慢。我以前从未使用过 ColorMatix。请向我们展示它如何与 ColorMatrix 一起使用。
  • Here 是一些示例帖子..
  • 谢谢。现在我看到上面的链接也显示了一个例子。
  • 我的背景是透明的,但它工作正常,无论如何,如果有人用 ColoMatrix 找到更好的解决方案,我会很高兴看到一些例子
猜你喜欢
  • 2011-09-19
  • 2020-04-11
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 2013-04-28
  • 2020-07-31
  • 2019-03-13
  • 1970-01-01
相关资源
最近更新 更多