我已经被这个问题困扰好几天了。为什么在此转换方法中出现“值未落在预期范围内
”异常? (这是 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
中的错误 - 它返回无效的 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);
关于c# - 打开 RandomAccessStream 时为 "Value does not fall within the expected range",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30133552/