如何在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中?我怎么能这样做?
非常感谢!
答案 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;
更新:
另一个参考..可能有所帮助:
更新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