Easily save a WriteableBitmap in WPF and C#


In my post Save bitmap files in WPF and C# I lamented (okay, whined about) the cumbersomeness of saving a WriteableBitmap into a file in WPF.

Fortunately there’s a way you can make it easier. Simply add an extension method to the WriteableBitmap class that writes it into a bitmap file. 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();

The 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 that 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.

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.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in extension methods, graphics, image processing, wpf, XAML and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

1 Response to Easily save a WriteableBitmap in WPF and C#

  1. Pingback: Save WriteableBitmap images in multiple formats in WPF and C# - C# HelperC# Helper

Comments are closed.