0

我有新闻列表,其中包含缩略图:

例子

我从服务器获取 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 中看到它

4

1 回答 1

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);
}
于 2013-07-26T09:30:32.410 回答