2011-08-04 177 views
1

如果我有一个到在线图像的链接,我想将图像源设置为此uri,我应该如何最好地做到这一点?我正在尝试的代码如下所示。
<Image Name="Poster" Height="400" Width="250" VerticalAlignment="Top" Margin="0,10,8,0"/>将图像源设置为URI

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

另外,如果我想缓存此图片再次装入这是怎么完成的?
谢谢

回答

5

这是正确的做法。如果您想要缓存图像供以后重复使用,可以随时将其下载到独立存储中。使用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; 
} 
+0

当我运行此我得到一个异常说: 相对URI不能因为创建'uriString'参数表示绝对URI。 – Ameen

+0

你传递了​​什么URI,抛出的异常究竟在哪里? –

+0

这是我通过的Uri: 'http://www.foo-web.net/res2/Adele Blanc - Sec.foob' 而且这个声明发生异常: 'imgSource.UriSource = new Uri(movie.B_Poster,UriKind.Relative);' – Ameen

1

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

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

0

你在代码隐藏中设置图像源的方式绝对没问题。另一种选择,如果你正在使用绑定/ 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(); 
    } 
}