“值不在预期范围内"打开 RandomAccessStream 时 [英] "Value does not fall within the expected range" when opening RandomAccessStream

查看:37
本文介绍了“值不在预期范围内"打开 RandomAccessStream 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为这个问题苦苦挣扎了好几天.为什么在这种转换方法中会出现Value does not fall in the expected range"异常?(它是 Windows Phone 8.1 应用)

I have been struggling with this problem for days. Why do I get "Value does not fall within the expected range" exception in this conversion method? (it's windows phone 8.1 app)

public static async Task<string> ConvertToBase64(this BitmapImage bitmapImage)
{
    RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
    var streamWithContent = await rasr.OpenReadAsync(); //raises an exception
    byte[] buffer = new byte[streamWithContent.Size];
    var result = await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
    using (MemoryStream ms = new MemoryStream(result.ToArray()))
    {
        return Convert.ToBase64String(ms.ToArray());
    }
}

我从资源中检索图像:

Photo = new BitmapImage(new Uri("ms-appx:///Assets/pies.jpg", UriKind.RelativeOrAbsolute));
        newOffer.PhotoBase64 = await Photo.ConvertToBase64();

推荐答案

这似乎是 BitmapImage.UriSource 中的一个错误——它返回了一个无效的 URI:

This appears to be a bug in BitmapImage.UriSource -- it returns an invalid URI:

var u1 = new Uri("ms-appx:///Assets/Logo.scale-240.png");
var u2 = new Uri("ms-appx:///Assets/Logo.scale-240.png");

// doesn't assert, because they are equal
Debug.Assert(u1 == u2, "URIs don't match"); 

BitmapImage bi = new BitmapImage(u1);
var u3 = bi.UriSource;

// asserts, because they are not equal
Debug.Assert(u1 == u3, "URIs don't match"); 

在这种情况下,u3 包含 ms-appx:/Assets/Logo.scale-240.png —— 缺少额外的斜线.你可以这样修复:

In this case, u3 contains ms-appx:/Assets/Logo.scale-240.png -- missing the extra slashes. You can fix like this:

var fixedUri = new Uri(u3.Scheme + "://" + u3.AbsolutePath);

这篇关于“值不在预期范围内"打开 RandomAccessStream 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆