Reputation: 13063
I'm looking for a way to draw a bitmap to a WPF DrawingContext as greyscale. I'd like to be able to draw it at the given x,y location and scale it to a given width and height. 256 levels of grey (8-bit greyscale) is good enough. I have a colour bitmap file on disk which will be either bmp, png or jpg format.
Upvotes: 1
Views: 1159
Reputation: 3461
You can do this using an effect - possibly not as performant as pure code, but offers flexibility.
<Image Source="../Images/ChartSample.png" Stretch="Uniform" Margin="5">
<Image.Effect>
<ee:ColorToneEffect DarkColor="Black" LightColor="White" ToneAmount="0" Desaturation="1" />
</Image.Effect>
Where you reference namespace as
xmlns:ee=”http://schemas.microsoft.com/expression/2010/effects”
Upvotes: 0
Reputation: 13063
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));
}
Upvotes: 2