c# UWP - 将字节数组转换为 InMemoryRandomAccessStream/IRandomAccessStream

标签 c# xaml uwp windows-8 microsoft-metro

我在 Windows 8 中将字节数组转换为 InMemoryRandomAccessStreamIRandomAccessStream 时遇到问题?

这是我的代码,但它不起作用:

internal static async Task<InMemoryRandomAccessStream> ConvertTo(byte[] arr) 
{
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    
    Stream stream = randomAccessStream.AsStream();
    
    await stream.WriteAsync(arr, 0, arr.Length);
    await stream.FlushAsync();

    return randomAccessStream;
}

然后我创建了 RandomAccessStreamReference 并设置了请求数据包以便将图像共享给其他应用

private static async void OnDeferredImageStreamRequestedHandler(DataProviderRequest Request) 
{
    DataProviderDeferral deferral = Request.GetDeferral();
    InMemoryRandomAccessStream stream = await ConvertTo(arr);
    
    RandomAccessStreamReference referenceStream =
            RandomAccessStreamReference.CreateFromStream(stream);
    
    Request.SetData(referenceStream);
}

没有异常(exception),但我不能使用结果图像字节数组

我认为将 byte[] 转换为 InMemoryRandomAccessStream 时出错,但不会抛出异常。

有人知道如何实现吗?

如果有人知道如何将字节数组转换为IRandomAccessStream,也将不胜感激

最佳答案

在 Windows 8.1 上,由于我们添加了 AsRandomAccessStream 扩展方法,它变得更加容易:

internal static IRandomAccessStream ConvertTo(byte[] arr)
{
    MemoryStream stream = new MemoryStream(arr);
    return stream.AsRandomAccessStream();
}

关于c# UWP - 将字节数组转换为 InMemoryRandomAccessStream/IRandomAccessStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16397509/

相关文章:

xaml - UWP xaml : How to display a button with icon and text in it?

uwp - 如何在不使用 FilePicker 的情况下在固定位置保存和加载 InkCanvas gif 文件

c# - 如何为 API 配置注入(inject)第二个 databaseContext

c# - c# 中的框架接口(interface)列表

c# - 一个关于 LINQ to XML 的简单问题

wpf - 将 <object property ="{StaticResource key}".../> 中的 Key 绑定(bind)到一个值

c# - 是否可以告诉 WPF 绑定(bind)异步响应 PropertyChanged 事件(低优先级)?

c# - Xamarin.Forms Picker ItemsSource在XAML中保持为空

c# - 一道C#语法问题

authentication - 如何正确使用WebAuthenticationCoreManager获取Microsoft帐户 token ?