[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Save bitmap files in WPF and C#

[Save bitmap files in WPF and C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.