问题
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());
}
}
I retrieve image from resources:
Photo = new BitmapImage(new Uri("ms-appx:///Assets/pies.jpg", UriKind.RelativeOrAbsolute));
newOffer.PhotoBase64 = await Photo.ConvertToBase64();
回答1:
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");
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);
来源:https://stackoverflow.com/questions/30133552/value-does-not-fall-within-the-expected-range-when-opening-randomaccessstream