Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 320
JMK Avatar asked Jan 04 '13 17:01

JMK


1 Answers

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();
like image 152
sa_ddam213 Avatar answered Nov 09 '22 05:11

sa_ddam213