如何在 Windows 8 中将字节数组转换为 InMemoryRandomAccessStream 或 IRandomAccessStream [英] How to convert byte array to InMemoryRandomAccessStream or IRandomAccessStream in windows 8
问题描述
现在我遇到了一个问题,即如何在 Windows 8 中将字节数组转换为 InMemoryRandomAccessStream 或 IRandomAccessStream?
now I've had a problem that is how to convert byte array to InMemoryRandomAccessStream or IRandomAccessStream in windows 8?
这是我的代码,但它不起作用,请参考以下代码
This is my code, but It did't work, refer the following code
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 并设置了请求数据包,以便将图像共享给其他应用程序
And then I create the RandomAccessStreamReference and set the requst datapack in order to share the image to other app
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 时会发生错误,但并没有抛出异常.
But the result is I can't share the image byte array to other app, Does my code have a problem? In my opinion, the error occurs when convert byte[] to InMemoryRandomAccessStream, but it did't throw exception.
有人知道怎么做吗?而且,如果您可以将字节数组转换为 IRandomAccessStream,同样可以帮助我.还是我的代码中的另一个错误?
Anybody know how to do it? And also if you can convert the byte array to IRandomAccessStream, the same can help me. Or another error in my code?
推荐答案
在文档顶部添加 using
语句.
Add the using
statement at the top of the document.
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;
}
这篇关于如何在 Windows 8 中将字节数组转换为 InMemoryRandomAccessStream 或 IRandomAccessStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!