将图像源设置为URI

如果我有一个在线图像的链接,我想将图像源设置为这个uri,我该如何做到最好? 我正在尝试的代码如下所示。

BitmapImage imgSource = new BitmapImage();
imgSource.UriSource = new Uri(movie.B_Poster, UriKind.Relative);
Poster.Source = imgSource;

此外,如果我想缓存此图像再次加载它是如何完成的?
谢谢

这是正确的方法。 如果要缓存映像以供以后重复使用,可以始终在隔离存储中下载它。 将WebClientOpenReadAsync – 传递图像URI并将其存储在本地。

 WebClient client = new WebClient(); client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); client.OpenReadAsync(new Uri("IMAGE_URL")); void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication(); using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Create, file)) { byte[] buffer = new byte[1024]; while (e.Result.Read(buffer, 0, buffer.Length) > 0) { stream.Write(buffer, 0, buffer.Length); } } } 

阅读它将是另一种方式:

 using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Open, file)) { BitmapImage image = new BitmapImage(); image.SetSource(stream); image1.Source = image; } 

你做得对了。

要缓存图像,您可以使用WebClient (最简单)或使用WebRequestWebResponse机制将其下载到本地文件存储。 然后,下次去设置图像位置时,检查它是否存在于本地。 如果是这样,请将其设置为本地文件。 如果没有,请将其设置为远程文件并下载。

PS。 您需要跟踪这些并删除旧文件,否则您将很快填满手机的内存。

在代码隐藏中设置图像源的方式绝对没问题。 另一种方法是,如果您使用绑定/ MVVM,则使用转换器将字符串URL转换为图像源:

 public class StringToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string url = value as string; Uri uri = new Uri(url); return new BitmapImage(uri); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }