将 RenderTargetBitmap 转换为 BitmapImage

Convert a RenderTargetBitmap to BitmapImage

如何在 C# XAML、Windows 8.1 中将 RenderTargetBitmap 转换为 BitmapImage?

我试过了

// 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);

但是总是在

报错
img.SetSourceAsync(randomAccessStream);

WPF有很多方法,但WinRT呢?我该怎么做?

非常感谢!

你试过这个吗:

  var bitmap = new  RenderTargetBitmap();

  await bitmap.RenderAsync(elementToRender);

  image.Source = bitmap;

参考:http://social.technet.microsoft.com/wiki/contents/articles/20648.using-the-rendertargetbitmap-in-windows-store-apps-with-xaml-and-c.aspx

更新:

另一个参考.. 可能有帮助:

更新 2:

试试这个:

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;
    }

参考:C# Windows 8 Store (Metro, WinRT) Byte array to BitmapImage

这是有效的 Sharing render to bitmap image in windows phone 8.1

原来我无法直接使用

填充流
stream.WriteAsync(byteArray.AsBuffer());

你必须使用位图编码器,最终工作代码:

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;