Reputation: 2976
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!
Upvotes: 1
Views: 3263
Reputation: 2976
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;
Upvotes: 3
Reputation: 1775
Have you tried this :
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(elementToRender);
image.Source = bitmap;
UPDATE :
Another Refs.. may help :
UPDATE 2 :
Try this one :
private async Task<BitmapImage> ByteArrayToBitmapImage(byte[] byteArray)
{
var bitmapImage = new BitmapImage();
var stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(byteArray.AsBuffer());
stream.Seek(0);
bitmapImage.SetSource(stream);
return bitmapImage;
}
Ref : C# Windows 8 Store (Metro, WinRT) Byte array to BitmapImage
Upvotes: 1