【问题标题】:Image to string图片转字符串
【发布时间】:2013-07-26 17:30:32
【问题描述】:

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

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

【问题讨论】:

  • 你的代码哪里出错了?
  • 你有没有使用断点来查看哪个对象是空的..
  • 我什至尝试使用我项目中的这张图片: BitmapImage image = new BitmapImage(new Uri("RTUTheme/MenuButton.png", UriKind.Relative));但是 NullRef 仍然失败 - 但我知道图像存在,如果它是 nul 我不会在 ImageBox 中看到它
  • 可能跟图片的状态有关。如果图像在显示之前被访问,则它不会被渲染,因此它可能会在内部行很长的某个地方触发该异常。看看有没有办法在创建BitmapImage对象的时候预加载图片。
  • 这并不能解决您的问题,因为之前发生过错误,但我只想指出,如果您想将图片保存到手机中,则无需将其转换为基数 64。将二进制流直接保存到隔离存储中。

标签: c# windows-phone-7 windows-phone-8


【解决方案1】:

问题是需要加载图像。您可以尝试保存第一次显示的图像:

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);
}

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2020-09-25
    相关资源
    最近更新 更多