从 url 下载图像并在 wp7 中的图像控件中打开它



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

我在做什么:使用Web客户端下载图像

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

但是我无法设置位图图像的来源。它抛出系统异常,没有什么具体的。我的做法是否正确?我的意思是程序。

编辑 另一个观察结果是 fileStreamLength 和 fileStreamLength2 是不同的。

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

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

最新更新