c# - 打开 RandomAccessStream 时为 "Value does not fall within the expected range"

标签 c# windows-phone-8.1 .net-4.5

我已经被这个问题困扰好几天了。为什么在此转换方法中出现“值未落在预期范围内”异常? (这是 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/

相关文章:

c# - 在 SQL Server 数据库中保存字体的最佳方法

c# - Windows Phone 8.1 在图像上写文字

c# - 转换器无法将类型 'system.datetime' 的值转换为 Windows Phone 8.1 Datepicker 中的类型 'datetime'

.net-4.5 - Roslyn 与 .net 4.5.2

c# - 在 C# 应用程序中显示 html/css 网页?

c# - for 和 foreach 在闭包方面有什么区别

c# - C# 中的特殊 Method 方法定义

xaml - 转到 Listivew 项目 DateTemplate Windows Phone 8.1 中的 VisualState

c# - 在 DisplayNameAttribute 派生类中获取属性和类名

c# - ASP.Net MVC 验证本地化不覆盖浏览器默认语言