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

19

我有一个问题,无法将字节数组转换为 InMemoryRandomAccessStreamIRandomAccessStream 在 Windows 8 中?

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

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

没有任何例外,但我无法使用结果图像的字节数组

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

有人知道如何实现吗?

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


你的代码出了什么问题? - Security Hound
请查看这个链接并告诉我您是否能解决这个问题。 - Farhan Ghumra
3个回答

27

在Windows 8.1中,我们添加了AsRandomAccessStream扩展方法,因此这变得更加容易:

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

1
这似乎对某些情况不起作用,如 https://dev59.com/933aa4cB1Zd3GeqPdnqj 中所述。 - tibel

25
在文档顶部添加using语句。
using System.Runtime.InteropServices.WindowsRuntime;
internal static async Task<InMemoryRandomAccessStream> ConvertTo(byte[] arr)
{
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    await randomAccessStream.WriteAsync(arr.AsBuffer());
    randomAccessStream.Seek(0); // Just to be sure.
                    // I don't think you need to flush here, but if it doesn't work, give it a try.
    return randomAccessStream;
}

6
一句话概括:
internal static IRandomAccessStream ConvertTo(byte[] arr)
{
    return arr.AsBuffer().AsStream().AsRandomAccessStream();
}

看起来是复制数据三次的操作。为了得到可用的答案,你需要检查这是否发生。 - Konstantin S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接