【问题标题】:Draw a colour bitmap as greyscale in WPF在 WPF 中将彩色位图绘制为灰度
【发布时间】:2014-09-10 01:02:39
【问题描述】:

我正在寻找一种将位图绘制到 WPF DrawingContext 作为灰度的方法。我希望能够在给定的 x,y 位置绘制它并将其缩放到给定的宽度和高度。 256 级灰度(8 位灰度)就足够了。我在磁盘上有一个彩色位图文件,可以是 bmp、png 或 jpg 格式。

【问题讨论】:

    标签: c# .net wpf graphics bitmap


    【解决方案1】:
    using System;
    using System.Windows;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    
    void DrawBitmapGreyscale(DrawingContext dc, string filename, int x, int y, int width, int height)
    {
        // Load the bitmap into a bitmap image object
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.UriSource = new Uri(filename);
        bitmap.EndInit();
    
        // Convert the bitmap to greyscale, and draw it.
        FormatConvertedBitmap bitmapGreyscale = new FormatConvertedBitmap(bitmap, PixelFormats.Gray8, BitmapPalettes.Gray256, 0.0);
        dc.DrawImage(bitmapGreyscale, new Rect(x, y, width, height));
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用效果来做到这一点 - 性能可能不如纯代码,但提供了灵活性。

      <Image Source="../Images/ChartSample.png" Stretch="Uniform" Margin="5">
      <Image.Effect>
          <ee:ColorToneEffect DarkColor="Black" LightColor="White" ToneAmount="0" Desaturation="1" />
      </Image.Effect>
      

      你在哪里引用命名空间

      xmlns:ee=”http://schemas.microsoft.com/expression/2010/effects&#8221;
      

      【讨论】:

      • 非常有趣,谢谢。可能还有一种以编程方式执行此操作的方法,这正是我所需要的。
      • 好的。然后,您可以对控件使用 RenderTargetBitmap,但如果我们选择这样做,我们显然缺少一个更智能的选项:) - 就像我说的那样,它提供了更大的灵活性,但如果您不使用它,这很快就会成为开销。
      猜你喜欢
      • 2018-04-18
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多