现在我遇到的问题是如何在Windows 8中将字节数组转换为InMemoryRandomAccessStream或IRandomAccessStream?
这是我的代码,但它没有用,请参考以下代码
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并设置requst数据包以便将图像共享给其他应用
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,同样可以帮助我。或者我的代码中有其他错误?
答案 0 :(得分:25)
在Windows 8.1上,我们添加AsRandomAccessStream扩展方法更加容易:
internal static IRandomAccessStream ConvertTo(byte[] arr)
{
MemoryStream stream = new MemoryStream(arr);
return stream.AsRandomAccessStream();
}
答案 1 :(得分:21)
在文档顶部添加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;
}
答案 2 :(得分:5)
在一行中:
</script>