如何存储从Web接收的图像并将其显示在Windows Phone 7应用程序中

我在windows phone 7应用程序中构建我的第一个应用程序。 我有一个来自网络的图像,当点击图像时,我导航到另一个页面。 我的xaml代码是:

  

我的.cs代码是

 private void Image_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new Uri("/AAP.xaml", UriKind.Relative)); } 

现在的问题是我想存储图像,以便在离线时甚至可以查看它。 任何人都可以帮助我为此目的做什么修改。

这是一个如何做到这一点的工作示例。 逻辑如下:

  1. 在页面的构造函数中,调用LoadImage方法。
  2. 该方法将imageBrush的ImageSource设置为隔离存储中的映像(如果可用)。
  3. 如果图像不存在于独立存储中,则LoadImage方法将从Web下载图像并在下载完成时调用事件处理程序。
  4. 然后,事件处理程序( DownloadCompleted方法)将图像保存到Isolated Storage并再次调用LoadImage 。 有关接下来发生的事情,请参阅第2点。

您可能希望稍后改进它以实现MVVM并使用DataBinding。

参考文献: nickharris.net , geekchamp.com

 string imageName = "myImage.jpg"; string imageUrl = "http://sofzh.miximages.com/c%23/landing.png"; public MainPage() { InitializeComponent(); LoadImage(); } private void LoadImage() { BitmapImage bi = new BitmapImage(); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { //load image from Isolated Storage if it already exist if (myIsolatedStorage.FileExists(imageName)) { using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(imageName, FileMode.Open, FileAccess.Read)) { bi.SetSource(fileStream); imageBrushName.ImageSource = bi; } } //else download image to Isolated Storage else { WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(DownloadCompleted); wc.OpenReadAsync(new Uri(imageUrl, UriKind.Absolute), wc); } } } private void DownloadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null && !e.Cancelled) { try { using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(imageName); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(e.Result); WriteableBitmap wb = new WriteableBitmap(bitmap); // Encode WriteableBitmap object to a JPEG stream. Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); fileStream.Close(); } //after image saved to Iso storage, call LoadImage method again //so the method will set imageBrush's ImageSource to image in Iso storage LoadImage(); } catch (Exception ex) { //Exception handle appropriately for your app } } else { //Either cancelled or error handle appropriately for your app } }