我有新闻列表,其中包含缩略图:
我从服务器获取JSON,这意味着图片是 - 链接
我的插入图片的代码:
foreach (Article article in NewsList.Result.Articles)
{
NewsListBoxItem NLBI = new NewsListBoxItem();
NLBI.Title.Text = article.Title;
NLBI.Date.Text = US.UnixDateToNormal(article.Date.ToString());
NLBI.id.Text = article.Id.ToString();
if (article.ImageURL != null)
{
BitmapImage image = new BitmapImage(new Uri(article.ImageURL));
NLBI.Thumbnail.Source = image;
}
NewsListBox.Items.Add(NLBI);
}
如果我在离线模式下进入应用程序 - 它们不会出现,所以我需要保存它们,这是最喜欢的方法 - 作为字符串!
这意味着我需要将它们转换为Base64:
BitmapImage image = new BitmapImage(new Uri(article.ImageURL));
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(image );
wbitmp .SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
bytearray = ms.GetBuffer();
}
string str = Convert.ToBase64String(bytearray);
代码失败,NullReferenceException
我的错误在哪里?
代码在线失败:
WriteableBitmap wbitmp = new WriteableBitmap(image);
错误:
System.Windows.ni.dll中发生了'System.NullReferenceException'类型的异常,但未在用户代码中处理
我甚至试图在我的项目中使用此图片:
BitmapImage image = new BitmapImage(new Uri("Theme/MenuButton.png",UriKind.Relative));
但仍然无法使用NullRef - 但我知道图像存在,如果它是nul我不会在ImageBox中看到它
答案 0 :(得分:0)
问题是需要加载图像。您可以尝试在第一次显示图像时保存图像:
foreach (Article article in NewsList.Result.Articles)
{
NewsListBoxItem NLBI = new NewsListBoxItem();
NLBI.Title.Text = article.Title;
NLBI.Date.Text = US.UnixDateToNormal(article.Date.ToString());
NLBI.id.Text = article.Id.ToString();
if (article.ImageURL != null)
{
BitmapImage image = new BitmapImage(new Uri(article.ImageURL));
image.ImageOpened += (s, e) =>
{
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(image );
wbitmp .SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
bytearray = ms.ToArray();
}
string str = Convert.ToBase64String(bytearray);
};
NLBI.Thumbnail.Source = image;
}
NewsListBox.Items.Add(NLBI);
}