sharmila sharmila - 5 months ago 271
C# Question

Convert RenderTargetBitmap to BitmapImage

I have a

, I need to convert it to
. Please check the code below.

RenderTargetBitmap bitMap = getRenderTargetBitmap();
Image image = new Image();// This is a Image
image.Source = bitMap;

In the above code I have used Image.Now I need to use a BitmapImage. How can I do this?

RenderTargetBitmap bitMap = getRenderTargetBitmap();
BitmapImage image = new BitmapImage();// This is a BitmapImage
// how to set bitMap as source of BitmapImage ?


Although it doesn't seem to be necessary to convert a RenderTargetBitmap into a BitmapImage, you could easily encode the RenderTargetBitmap into a MemoryStream and decode the BitmapImage from that stream.

There are several BitmapEncoders in WPF, the sample code below uses a PngBitmapEncoder.

var renderTargetBitmap = getRenderTargetBitmap();
var bitmapImage = new BitmapImage();
var bitmapEncoder = new PngBitmapEncoder();

using (var stream = new MemoryStream())
    stream.Seek(0, SeekOrigin.Begin);

    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = stream;