7

How do I convert a WriteableBitmap object to a BitmapImage Object in WPF?

This link covers silverlight, the process is not the same in WPF as the WriteableBitmap object does not have a SaveJpeg method.

So my question is How do I convert a WriteableBitmap object to a BitmapImage Object in WPF?

Community
  • 1
  • 1
JMK
  • 27,273
  • 52
  • 163
  • 280
  • 1
    See [this answer](http://stackoverflow.com/a/13988871/1136211) and replace RenderTargetBitmap by WriteableBitmap. Why exactly do you need this conversion? It's usually not necessary, since BitmapImage and WriteableBitmap have a common base class BitmapSource which provides all relevant properties of an image. – Clemens Jan 04 '13 at 17:27

1 Answers1

16

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

In this example we will use the PngBitmapEncoder but just choose the one that fits 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;
}

usage:

 BitmapImage bitmap = ConvertWriteableBitmapToBitmapImage(your writable bitmap);

or you could make this an extension method for easy 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;
    }
}

usage:

WriteableBitmap wbm = // your writeable bitmap

BitmapImage bitmap = wbm.ToBitmapImage();
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
  • 1
    And don't forget to rewind the stream. After saving, before setting `bmImage.StreamSource` do a `stream.Seek(0, SeekOrigin.Begin);`. Some decoders (e.g. JPG) require this. See also [here](http://stackoverflow.com/a/13988871/1136211). – Clemens Jan 04 '13 at 21:57
  • Thankyou both, most helpful! – JMK Jan 04 '13 at 22:36
  • @JMK Still i doubt that it's really necessary to do this conversion. – Clemens Jan 04 '13 at 23:21