【问题标题】:Download an image from url and opening it in an image control in wp7从 url 下载图像并在 wp7 的图像控件中打开它
【发布时间】:2012-04-25 16:26:34
【问题描述】:

我正在制作一个 WP7 应用程序,它可以下载我所有的 Twitter 提要。在此,我想下载所有个人资料图像并将它们存储在本地并使用它们,以便每次打开应用程序时都会下载它们。请提出任何这样做的方法。

我在做什么:使用 WebClient 下载图像

public MainPage()
    {
        InitializeComponent();

        WebClient client = new WebClient();
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        client.DownloadStringAsync(new Uri("http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg"));
    }

并将其存储到文件中。

 void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {            
        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (myIsolatedStorage.FileExists(fileName1))
                myIsolatedStorage.DeleteFile(fileName1);


            var fileName1 = "Image.jpg";
            using (var fileStream = new IsolatedStorageFileStream(fileName1, FileMode.Create, myIsolatedStorage))
            {
                using (var writer = new StreamWriter(fileStream))
                {
                    var length = e.Result.Length;
                    writer.WriteLine(e.Result);
                }
                var fileStreamLength = fileStream.Length;
                fileStream.Close();
            }
        }

现在我正在尝试将图像设置为 BitMapImage

BitmapImage bi = new BitmapImage();

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName1, FileMode.Open, FileAccess.Read))
    {
         var fileStreamLength2 = fileStream.Length;
         bi.SetSource(fileStream);
    }
}

但我无法设置 BitmapImage 的来源。它抛出 System.Exception 并没有什么特别的。我做对了吗?我的意思是程序。

EDIT另一个观察是fileStreamLength和fileStreamLength2是不同的。

【问题讨论】:

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


【解决方案1】:

您不应该使用 DownloadString 来下载二进制文件。请改用 OpenReadAsync,并将二进制数组保存到隔离存储中。

DownloadString 会尝试将您的数据转换为 UTF-16 文本,这在处理图片时当然不可能正确。

【讨论】:

  • 谢谢,伙计。这很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 2013-03-12
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多