BLOG.CSHARPHELPER.COM: Write an extension method to make saving a WriteableBitmap into a file easy using WPF and C#
Write an extension method to make saving a WriteableBitmap into a file easy using WPF and C#
In my post Create a bitmap and save it into a file using WPF, XAML, and C# I lamented (okay, whined) about how cumbersome it is to save a WriteableBitmap into a file. Fortunately there's a way you can make it easier. Simply add an extension method to the WriteableBitmap class. The following code shows such a method.
public static class WriteableBitmapExtentions
{
// Save the WriteableBitmap into a PNG file.
public static void Save(this WriteableBitmap wbitmap, string filename)
{
// Save the bitmap into a file.
using (FileStream stream = new FileStream(filename, FileMode.Create))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbitmap));
encoder.Save(stream);
}
}
}
This "this WriteableBitmap wbitmap" part of the method declaration means this method extends the WriteableBitmap class. The parameter wbitmap represents the WriteableBitmap object for which you called the method. The second parameter, filename, is the only one you actually pass into the method.
The method creates a FileStream to hold the saved PNG file. It creates a PngBitmapEncoder to write the file's bitmap data. It then calls BitmapFrame.Create to create a new bitmap frame for the WriteableBitmap, and it adds the result to the encoder's Frames collection. The code finishes by saving the encoder's data into the FileStream.
The blue statement in the following code shows how the main program uses this method to save a WriteableBitmap into a PNG file.
// Convert the pixel data into a WriteableBitmap.
WriteableBitmap wbitmap = bm_maker.MakeBitmap(96, 96);
...
// Save the bitmap into a file.
wbitmap.Save("ColorSamples.png");
It would have been nice if Microsoft had included this functionality in the WriteableBitmap class, but at least it's easy to add this feature with an extension method.
Comments