Search code examples
c#xamlwindows-runtimebitmapimagerendertargetbitmap

Convert a RenderTargetBitmap to BitmapImage


How can I convert a RenderTargetBitmap to BitmapImage in C# XAML, Windows 8.1?

I tried

// rendered is the RenderTargetBitmap 
BitmapImage img = new BitmapImage();
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
await randomAccessStream.WriteAsync(await rendered.GetPixelsAsync());
randomAccessStream.Seek(0); 
await img.SetSourceAsync(randomAccessStream);

But it always gives error at

img.SetSourceAsync(randomAccessStream);

There are many ways in WPF but in WinRT? How can I do that ?

Thanks a lot!


Solution

  • this is the one that worked Sharing render to bitmap image in windows phone 8.1

    turned out that i just can't fill the stream directly using

    stream.WriteAsync(byteArray.AsBuffer());
    

    you have to use bitmap encoder , final working code :

    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            var buffer = await rendered.GetPixelsAsync();
          //  await stream.ReadAsync(buffer, (uint)buffer.Length, InputStreamOptions.None);
            BitmapImage img = new BitmapImage();
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
            encoder.SetPixelData(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                (uint)rendered.PixelWidth,
                (uint)rendered.PixelHeight,
                DisplayInformation.GetForCurrentView().LogicalDpi,
                DisplayInformation.GetForCurrentView().LogicalDpi,
                buffer.ToArray());
            await encoder.FlushAsync();
            await img.SetSourceAsync(stream);
            preview.Source = img;