Save bitmap files in WPF and C#

[save bitmap files]

This example shows how to use WPF and C# to save bitmap files. The example Set the pixels in a WPF bitmap in C# shows how to create a WriteableBitmap in WPF. This example shows how to save the resulting bitmap.

Like many things in WPF, this is not as easy as it used to be. In a Windows Forms application, you simply call the Bitmap object’s Save method.

The following code shows how the program saves bitmap files. The code from the previous example that creates the WriteableBitmap has been omitted.


private void Window_Loaded(object sender, RoutedEventArgs e)
{
    // Make the WriteableBitmap.
    ...

    // Save the bitmap into a file.
    using (FileStream stream =
        new FileStream("ColorSamples.png", FileMode.Create))
    {
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(wbitmap));
        encoder.Save(stream);
    }

    // Tell the user we're done.
    MessageBox.Show("Done");
}

After creating the bitmap, the program creates a FileStream object associated with the file that should hold the bitmap. It creates a PngBitmapEncoder to write the object. It then calls BitmapFrame.Create to create a new bitmap frame for the WriteableBitmap, and adds the result to the encoder’s Frames collection. The code finishes by saving the encoder’s data into the FileStream.

Not very simple or intuitive, but it shouldn’t be hard to copy and paste this code when you need your program to save bitmap files.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in files, graphics, image processing and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

3 Responses to Save bitmap files in WPF and C#

  1. 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) { …

  2. Pingback: Easily manipulate pixels in WPF and C# - C# HelperC# Helper

  3. Pingback: Easily save a WriteableBitmap in WPF and C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.