"Value does not fall within the expected range" 打开 RandomAccessStream 时

"Value does not fall within the expected range" when opening RandomAccessStream

几天来我一直在为这个问题苦苦挣扎。为什么在这种转换方法中会出现“Value does not fall within the expected range”异常? (它是 windows phone 8.1 应用程序)

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 中的错误 -- 它 returns 一个无效的 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 -- 缺少额外的斜杠。您可以这样修复:

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