“Value does not fall within the expected range” when opening RandomAccessStream

我的梦境 提交于 2019-12-13 17:04:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!