Create a bitmap and save it into a file using WPF, XAML, and C#

The example Set the pixels in a bitmap using WPF, XAML, and C# shows how to create a WriteableBitmap in WPF. This example shows how to save the bitmap into a file. (Like many things in WPF, it's not as easy as it used to be. In a Windows Forms application, you simply call the Bitmap's Save method.)

The following code shows how the program works. 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 it.

   

 

What did you think of this article?




Trackbacks
  • 3/28/2014 12:25 PM BLOG.CSHARPHELPER.COM wrote:
    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) { ...
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.