我几天来一直在努力解决这个问题。为什么我会得到" Value does not fall within the expected range
"此转换方法中的异常? (它的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();
答案 0 :(得分:2)
这似乎是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);