How to convert a WriteableBitmap object to a BitmapImage object in WPF

How to convert a WriteableBitmap object to a BitmapImage object in WPF?

This link covers silverlight, the process does not match the WPF process, since the WriteableBitmap object does not have a SaveJpeg method.

So my question is: How to convert a WriteableBitmap object to a BitmapImage object in WPF?

+7
source share
1 answer

You can use one of BitmapEncoders to save the WriteableBitmap frame to the new BitmapImage

In this example, we will use PngBitmapEncoder , but just select the one that suits your situation.

 public BitmapImage ConvertWriteableBitmapToBitmapImage(WriteableBitmap wbm) { BitmapImage bmImage = new BitmapImage(); using (MemoryStream stream = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(wbm)); encoder.Save(stream); bmImage.BeginInit(); bmImage.CacheOption = BitmapCacheOption.OnLoad; bmImage.StreamSource = stream; bmImage.EndInit(); bmImage.Freeze(); } return bmImage; } 

using:

  BitmapImage bitmap = ConvertWriteableBitmapToBitmapImage(your writable bitmap); 

or you can do it by extension method for ease of use

 public static class ImageHelpers { public static BitmapImage ToBitmapImage(this WriteableBitmap wbm) { BitmapImage bmImage = new BitmapImage(); using (MemoryStream stream = new MemoryStream()) { PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(wbm)); encoder.Save(stream); bmImage.BeginInit(); bmImage.CacheOption = BitmapCacheOption.OnLoad; bmImage.StreamSource = stream; bmImage.EndInit(); bmImage.Freeze(); } return bmImage; } } 

using:

 WriteableBitmap wbm = // your writeable bitmap BitmapImage bitmap = wbm.ToBitmapImage(); 
+11
source

All Articles