将RenderTargetBitmap转换为BitmapImage

时间:2015-10-05 11:16:32

标签: c# xaml windows-runtime bitmapimage rendertargetbitmap

如何在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中?我怎么能这样做?

非常感谢!

2 个答案:

答案 0 :(得分:2)

这是有效的 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;

答案 1 :(得分:1)

你试过这个:

  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